循环链表
循环链表 (Circular Linked List)
3. 循环链表(Circular Linked List)
定义:单链表的变种,最后一个节点的
next指向头节点,形成闭环。性质:
- 支持从任意节点开始遍历整个链表。
- 常用于需要循环访问的场景(如操作系统的任务调度)。
Java 实现:
class CNode { int data; CNode next; CNode(int data) { this.data = data; this.next = null; } } class CircularLinkedList { private CNode head; // 在头部插入 public void insertAtBeginning(int data) { CNode newNode = new CNode(data); if (head == null) { newNode.next = newNode; // 自己指向自己 head = newNode; return; } CNode last = head; while (last.next != head) { last = last.next; } newNode.next = head; last.next = newNode; head = newNode; } }