以下是一个使用Java实现的双向循环链表的示例:
class Node {
int data;
Node prev;
Node next;
public Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
class DoublyCircularLinkedList {
private Node head;
private Node tail;
public DoublyCircularLinkedList() {
this.head = null;
this.tail = null;
}
public void insertAtFront(int data) {
Node newNode = new Node(data);
if (head == null) {
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 insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
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 display() {
if (head == null) {
System.out.println("Doubly circular linked list is empty.");
return;
}
Node current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
DoublyCircularLinkedList dcll = new DoublyCircularLinkedList();
dcll.insertAtFront(3);
dcll.insertAtFront(2);
dcll.insertAtFront(1);
dcll.insertAtEnd(4);
dcll.insertAtEnd(5);
dcll.display(); // Output: 1 2 3 4 5
}
}
在上述示例中,我们首先定义了一个Node
类,用于表示双向循环链表中的节点。每个节点包含一个整数类型的data
字段,以及指向前一个节点和后一个节点的prev
和next
指针。
然后,我们定义了DoublyCircularLinkedList
类,作为双向循环链表的主要实现。该类包含head
和tail
两个节点指针,用于表示链表的头部和尾部。
我们实现了insertAtFront
方法和insertAtEnd
方法,用于在链表的头部和尾部插入节点。在插入节点时,我们更新相应的指针以建立节点之间的双向循环连接。
最后,在Main
类中,我们创建了一个双向循环链表对象dcll
,并使用insertAtFront
和insertAtEnd
方法插入了一些节点。然后调用display
方法来打印出链表中的所有节点数据。
运行示例代码会输出:1 2 3 4 5,表示双向循环链表中节点的顺序。在循环链表中,我们可以从任
意一个节点出发,通过循环遍历访问到链表的所有节点。