Linked List Basics Quiz
Short prompts on singly vs doubly linked lists, traversal, length, and the everyday operations that come up before cycle detection or in-place reversal.
Question Bank
Easy
JavaScript
4 questions
linked-list
data-structures
quiz
fundamentals
874 views
13
What does this code print? Trace each step.
Examples
Example 1:
Input: head -> 1 -> 2 -> 3 -> null
Output: 1 2 3
Explanation: Walker cur starts at head, appends cur.value to out, then advances via cur.next until cur is null. The final trimmed string is '1 2 3'.class Node {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
const head = new Node(1, new Node(2, new Node(3)));
let cur = head;
let out = '';
while (cur) {
out += cur.value + ' ';
cur = cur.next;
}
console.log(out.trim());Implement length(head) returning the number of nodes in a singly linked list. What are its time and space complexity?
Examples
Example 1:
Input: head -> 1 -> 2 -> 3 -> null
Output: 3
Explanation: A single walker advances from head incrementing a counter until cur becomes null. Time is O(n), extra space O(1).Example 2:
Input: head = null
Output: 0
Explanation: With an empty list the loop body never runs and the counter stays at 0.function length(head) {
// TODO: return the number of nodes
}Implement insertAfter(node, value) that inserts a new node holding value immediately after node in a singly linked list. Return the new node.
Examples
Example 1:
Input: list = 1 -> 3 -> null, node = the node holding 1, value = 2
Output: list becomes 1 -> 2 -> 3 -> null; the call returns the new node holding 2
Explanation: Allocate fresh = new Node(value, node.next), then set node.next = fresh. Doing the two pointer writes in that order preserves the tail. Cost is O(1).class Node {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
function insertAfter(node, value) {
// TODO: splice a new node in after `node`
}Compare singly and doubly linked lists on three axes: per-node memory, reverse traversal, and removal cost when you only hold a pointer to the node to remove.
