In a circular linked list, the last node connects back to the first node, forming a circle. In a linear linked list, the last node points to null, marking the end.
class Node { int data; Node next; Node(int d) { data = d; next = null; } } public class CircularList { public static void main(String[] args) { Node head = new Node(1); Node second = new Node(2); Node third = new Node(3); head.next = second; second.next = third; third.next = head; // circular link Node current = head; for (int i = 0; i < 5; i++) { System.out.print(current.data + " "); current = current.next; } } }
The list nodes are 1 -> 2 -> 3 -> back to 1. Traversing 5 nodes cycles through 1, 2, 3, then again 1, 2.
class Node { int data; Node next; Node(int d) { data = d; next = null; } } public class LinearList { public static void main(String[] args) { Node head = new Node(1); Node second = new Node(2); head.next = second; Node current = head; while (current.next != null) { System.out.print(current.data + " "); current = current.next; } System.out.print(current.data + " "); } }
The loop runs while current.next is not null, printing current.data each time. When current.next is null (at last node), loop stops and last node data is printed after loop.
class Node { int data; Node next; Node(int d) { data = d; next = null; } } public class DetectCircular { public static boolean isCircular(Node head) { if (head == null) return false; Node slow = head, fast = head.next; while (fast != null && fast.next != null) { if (slow == fast) return true; slow = slow.next; fast = fast.next.next; } return false; } public static void main(String[] args) { Node head = new Node(1); Node second = new Node(2); Node third = new Node(3); head.next = second; second.next = third; third.next = head; // circular link System.out.println(isCircular(head)); } }
The fast and slow pointers will meet in a circular linked list, so the method returns true.
Each node in both lists stores one pointer to the next node. The difference is that in circular lists, the last node points back to the first node instead of null, but no extra memory is used.
