写一个双向循环链表的Java代码
时间: 2024-03-13 11:44:10 浏览: 17
下面是一个简单的双向循环链表的Java代码实现:
```java
public class DoublyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private static class Node<T> {
private T data;
private Node<T> prev;
private Node<T> next;
public Node(T data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
public DoublyLinkedList() {
head = null;
tail = null;
}
public boolean isEmpty() {
return head == null;
}
public void addFirst(T data) {
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
tail.next = head;
head.prev = tail;
}
public void addLast(T data) {
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
head = newNode;
tail = newNode;
} else {
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
}
tail.next = head;
head.prev = tail;
}
public void removeFirst() {
if (isEmpty()) {
throw new NoSuchElementException();
}
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
head.prev = tail;
tail.next = head;
}
}
public void removeLast() {
if (isEmpty()) {
throw new NoSuchElementException();
}
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.prev;
tail.next = head;
head.prev = tail;
}
}
public void printList() {
if (isEmpty()) {
System.out.println("List is empty!");
} else {
Node<T> current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
System.out.println();
}
}
}
```
这个代码实现了双向循环链表的基本操作,包括添加节点、删除节点和遍历链表。可以通过创建一个DoublyLinkedList对象来使用这些操作。