
在 单链表 中 ,
将 最后一个节点 的指针 指向 第一个节点 , 形成一个闭环 ,
上述 头尾相连 的单链表 称为 " 单循环链表 " ,
简称为 " 循环链表 " ;
在 循环链表 中 , 没有明确的 第一个节点 或 最后一个节点 ;
循环链表 可以 模拟 环形结构 数据 , 如 : 循环队列 ;
在下面的代码中 ,
使用 Java 语言实现 单循环链表 :
public class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class CircularLinkedList {
private Node head;
public CircularLinkedList() {
this.head = null;
}
public void append(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
head.next = head;
} else {
Node lastNode = head;
while (lastNode.next != head) {
lastNode = lastNode.next;
}
lastNode.next = newNode;
newNode.next = head;
}
}
public void printList() {
if (head == null) {
System.out.println("Circular Linked List is empty.");
return;
}
Node current = head;
do {
System.out.print(current.data + " ");
current = current.next;
} while (current != head);
}
public static void main(String[] args) {
CircularLinkedList cll = new CircularLinkedList();
cll.append(1);
cll.append(2);
cll.append(3);
cll.append(4);
cll.printList();
}
}