class Node { value: number; next: Node | null; constructor(value: number) { this.value = value; this.next = null; } } // Create circular linked list: 10 -> 20 -> 30 -> back to 10 const head = new Node(10); const second = new Node(20); const third = new Node(30); head.next = second; second.next = third; third.next = head; // Traverse and print values let current: Node | null = head; do { console.log(current.value); current = current.next; } while (current !== head);
The traversal uses a do-while loop that prints each node's value and moves to the next node. It stops when it reaches the head node again, so it prints 10, 20, and 30 exactly once each.
do-while loop preferred over a while loop when traversing a circular linked list starting from the head node?A do-while loop runs the loop body first before checking the condition. This is important for circular linked lists to process the head node before deciding to stop, avoiding missing the first node.
let current: Node | null = head;
while (current !== head) {
console.log(current.value);
current = current.next;
}The loop condition current !== head is false at the start because current is initialized to head. So the loop body never runs and no output is printed.
class Node { value: number; next: Node | null; constructor(value: number) { this.value = value; this.next = null; } } const head = new Node(1); const second = new Node(2); const third = new Node(3); head.next = second; second.next = third; third.next = head; // Insert new node with value 4 after node 2 const newNode = new Node(4); newNode.next = second.next; second.next = newNode; // Traverse and print let current: Node | null = head; do { console.log(current.value); current = current.next; } while (current !== head);
The new node with value 4 is inserted after node 2, so the order becomes 1 -> 2 -> 4 -> 3 -> back to 1. Traversal prints nodes in this order.
Since circular linked lists have no null next pointers, the traversal ends when the current node returns to the head node after visiting all nodes once.
