迴圈單鏈表(Circular linked list)的最後一個結點指向頭結點,形成一個環。因此,從迴圈連結串列中的任何一個結點出發都能找到任何其他結點。
迴圈單鏈表
通常來說,透過判斷節點是否為null來停止連結串列的遍歷,但是對於迴圈連結串列,再次到達初始節點才停止遍歷。
push函式進行連結串列的構建,每次都返回連結串列初始節點。
public class CircularLinkedList { static class Node { int data; Node next; } // Function to insert a node at the beginning of a // circular linked list. static Node push(Node head, int data) { Node newNode = new Node(); newNode.data = data; newNode.next = head; // If linked list is not null // then set the next of last node. // 最後一個元素指向最開始的元素 Node temp = head; if (head != null) { while (temp.next != head) temp = temp.next; temp.next = newNode; } else { // 指向自己 newNode.next = newNode; } head = newNode; return head; } public static void main(String[] args) { Node head = push(null, 12); head = push(head, 56); head = push(head, 2); head = push(head, 11); Node temp = head; if (head != null) { do { System.out.print(temp.data + " "); temp = temp.next; } while (temp != head); } }}
輸出
11 2 56 12