双向循环链表java
时间: 2023-12-31 20:24:15 浏览: 87
java双向循环链表的实现代码
以下是一个双向循环链表的Java实现示例:
```java
public class DoublyLinkedList {
private Node head;
private Node tail;
private class Node {
int val;
Node prev;
Node next;
public Node(int val) {
this.val = val;
}
}
public DoublyLinkedList() {
head = null;
tail = null;
}
public boolean isEmpty() {
return head == null;
}
public void insertAtHead(int val) {
Node newNode = new Node(val);
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 insertAtTail(int val) {
Node newNode = new Node(val);
if (isEmpty()) {
head = newNode;
tail = newNode;
newNode.next = newNode;
newNode.prev = newNode;
} else {
newNode.next = head;
newNode.prev = tail;
tail.next = newNode;
head.prev = newNode;
tail = newNode;
}
}
public void display() {
Node cur = head;
if (cur == null) {
System.out.println("双向链表为空");
return;
}
do {
System.out.print(cur.val + " ");
cur = cur.next;
} while (cur != head);
System.out.println();
}
}
```
使用示例:
```java
DoublyLinkedList list = new DoublyLinkedList();
list.insertAtHead(3);
list.insertAtHead(2);
list.insertAtHead(1);
list.insertAtTail(4);
list.insertAtTail(5);
list.display(); // 输出:1 2 3 4 5
```
阅读全文