java实现双向循环链表(附完整源码)
时间: 2023-10-17 10:10:14 浏览: 74
java中使用双向链表实现贪吃蛇程序源码分享
请参考以下代码:
```java
public class DoublyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private static class Node<T> {
private T value;
private Node<T> prev;
private Node<T> next;
public Node(T value) {
this.value = value;
}
}
public DoublyLinkedList() {
head = null;
tail = null;
}
public boolean isEmpty() {
return head == null;
}
public void addFirst(T value) {
Node<T> newNode = new Node<>(value);
if (isEmpty()) {
head = newNode;
tail = newNode;
newNode.next = newNode;
newNode.prev = newNode;
} else {
newNode.next = head;
newNode.prev = tail;
head.prev = newNode;
tail.next = newNode;
head = newNode;
}
}
public void addLast(T value) {
Node<T> newNode = new Node<>(value);
if (isEmpty()) {
head = newNode;
tail = newNode;
newNode.next = newNode;
newNode.prev = newNode;
} else {
newNode.next = head;
newNode.prev = tail;
head.prev = newNode;
tail.next = newNode;
tail = newNode;
}
}
public void removeFirst() {
if (!isEmpty()) {
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
head.prev = tail;
tail.next = head;
}
}
}
public void removeLast() {
if (!isEmpty()) {
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.prev;
tail.next = head;
head.prev = tail;
}
}
}
public void print() {
if (!isEmpty()) {
Node<T> current = head;
do {
System.out.print(current.value + " ");
current = current.next;
} while (current != head);
System.out.println();
}
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
DoublyLinkedList<Integer> list = new DoublyLinkedList<>();
list.addFirst(10);
list.addLast(20);
list.addFirst(5);
list.addLast(30);
list.print(); // 5 10 20 30
list.removeFirst();
list.removeLast();
list.print(); // 10 20
}
}
```
阅读全文