Which statement best describes the key difference between a circular linked list and a linear linked list?
Think about how the last node connects in each list type.
The main difference is how the last node links. In a circular linked list, the last node points back to the first node, creating a loop. In a linear linked list, the last node points to null, marking the end.
Consider this JavaScript code that creates a circular linked list with 3 nodes and traverses it once. What is the printed output?
class Node { constructor(value) { this.value = value; this.next = null; } } const node1 = new Node(1); const node2 = new Node(2); const node3 = new Node(3); node1.next = node2; node2.next = node3; node3.next = node1; // circular link let current = node1; let count = 0; let output = ''; while (count < 3) { output += current.value + ' -> '; current = current.next; count++; } output += 'null'; console.log(output);
The loop runs exactly 3 times, printing each node once.
The code traverses exactly 3 nodes starting from node1. It prints values 1, 2, 3 followed by 'null'. Even though the list is circular, the loop stops after 3 iterations.
What will be the output of this JavaScript code that creates a linear linked list and traverses it?
class Node { constructor(value) { this.value = value; this.next = null; } } const node1 = new Node(1); const node2 = new Node(2); const node3 = new Node(3); node1.next = node2; node2.next = node3; node3.next = null; // linear end let current = node1; let output = ''; while (current !== null) { output += current.value + ' -> '; current = current.next; } output += 'null'; console.log(output);
The loop continues until current is null, printing all nodes.
The code prints all nodes in the linear linked list: 1, 2, 3, then 'null' to mark the end.
Which of the following is the best reason to use a circular linked list instead of a linear linked list?
Think about how the last node connects back to the first node.
Circular linked lists allow continuous traversal without needing to reset to the head manually, making repeated looping easier.
What error will occur when running this code that tries to traverse a circular linked list without a stopping condition?
class Node { constructor(value) { this.value = value; this.next = null; } } const node1 = new Node(1); const node2 = new Node(2); const node3 = new Node(3); node1.next = node2; node2.next = node3; node3.next = node1; // circular link let current = node1; while (current !== null) { console.log(current.value); current = current.next; }
Consider what happens when the list loops back to the first node.
The loop condition checks for current !== null, but in a circular linked list, current never becomes null. This causes an infinite loop printing 1, 2, 3 repeatedly.
