Imagine you have a list of items that changes often by adding or removing items in the middle. Which problem does a linked list solve better than an array?
Think about what happens when you add or remove items in the middle of an array.
Arrays require shifting elements when inserting or deleting in the middle, which is slow. Linked lists just change pointers, making these operations faster.
What is the printed state of the linked list after these insertions?
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { constructor() { this.head = null; } insertAtHead(value) { const newNode = new Node(value); newNode.next = this.head; this.head = newNode; } printList() { let current = this.head; let result = ''; while (current) { result += current.value + ' -> '; current = current.next; } result += 'null'; console.log(result); } } const list = new LinkedList(); list.insertAtHead(3); list.insertAtHead(2); list.insertAtHead(1); list.printList();
New nodes are added at the head, so the last inserted is first in the list.
Each new node is inserted at the head, so the list order is 1, then 2, then 3, resulting in 1 -> 2 -> 3 -> null.
What error does this code cause when trying to print the linked list?
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { constructor() { this.head = null; } printList() { let current = this.head; while (current.next) { console.log(current.value); current = current.next; } } } const list = new LinkedList(); list.head = new Node(1); list.head.next = new Node(2); list.printList();
Look at the loop condition and what happens when current is the last node.
The loop stops when current.next is null, so the last node's value is never printed.
Which property of linked lists makes them suitable for implementing a stack data structure?
Think about how stacks add and remove items.
Stacks add and remove items at one end (top). Linked lists allow fast insertions and removals at the head, matching stack operations.
Why do linked lists generally use more memory than arrays for the same number of elements?
Think about what extra information each linked list node must keep.
Each linked list node stores the element plus a pointer to the next node, increasing memory usage compared to arrays which store elements contiguously without pointers.
