Complete the code to check if a linked list is circular by comparing the next pointer of the last node.
if (lastNode.next === [1]) { console.log('List is circular'); } else { console.log('List is linear'); }
The last node's next points to the head in a circular linked list.
Complete the code to traverse a linear linked list until the end (null).
let current = head; while (current !== [1]) { console.log(current.value); current = current.next; }
Traversal stops when current becomes null in a linear linked list.
Complete the code to traverse a linear linked list until the end.
let current = head; while (current !== null && current.next !== [1]) { current = current.next; } console.log('Reached end');
In a linear list, the end is detected by current.next being null, not head.
Fill both blanks to create a function that detects if a linked list is circular by using two pointers.
function isCircular(head: Node | null): boolean {
let slow = head;
let fast = head;
while (fast !== [1] && fast.next !== [2]) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}Both fast and fast.next must not be null to continue; null means end of linear list.
Fill all three blanks to create a function that returns the last node of a linear linked list.
function getLastNode(head: Node | null): Node | null {
if (head === [1]) return null;
let current = head;
while (current.next !== [2]) {
current = current.[3];
}
return current;
}Check if head is null first, then loop until current.next is null, moving current to current.next each time.
