Chapter 5: Linked Lists
Multiple Choice · Basics
Question 1: Kinds of Linked Lists
Which statement is true of a circular singly linked list?
In a circular list the last node points back to the first, not to null, so the list is a ring. A describes an ordinary singly linked list and B a doubly linked one. D is false: no linked list keeps its nodes contiguous; references set the order.
Short Answer · Basics
Question 2: Following the Links
What does this code print? Does the order in which the nodes are created with new affect the result?
Node a = new Node(10), b = new Node(20); Node c = new Node(30), d = new Node(40); c.next = a; a.next = d; d.next = b; Node head = c; for (Node g = head; g != null; g = g.next) System.out.print(g.data + " -> "); System.out.println("null");
Show answer
Output: 30 -> 10 -> 40 -> 20 -> null
The traversal starts at head = c (30) and follows the next references: 30 → 10 → 40 → 20. The next field of 20 is still null, so the list ends there.
The creation order (or the position in memory) does not matter: the nodes are not contiguous, and only the next fields set the order. head alone is enough to reach the list.
Multiple Choice · Basics
Question 3: Drawbacks Compared with Arrays
Which of the following is not a drawback of a singly linked list compared with an array?
D is a drawback of arrays; a linked list grows dynamically, one new per insertion. A, B, and C are the known costs of a linked list: no random access (the i-th item is O(n)), an extra reference per node, forward-only movement.
Short Answer · Basics
Question 4: Array and List Costs
Fill in the table with time complexities (O(1) or O(n)). The singly linked list keeps only head; the doubly linked list keeps head and tail. Explain why deleting at the tail differs between the singly and doubly linked lists.
| Operation | Array | Singly linked | Doubly linked |
|---|---|---|---|
| Access the i-th item | ? | ? | ? |
| Insert at the front | ? | ? | ? |
| Delete at the tail | ? | ? | ? |
Show answer
| Operation | Array | Singly linked | Doubly linked |
|---|---|---|---|
| Access the i-th item | O(1) | O(n) | O(n) |
| Insert at the front | O(n) | O(1) | O(1) |
| Delete at the tail | O(1) | O(n) | O(1) |
To delete at the tail, the next link of the second-to-last node must be set to null. In a singly linked list, reaching that node means walking from the head: O(n). In a doubly linked list, tail.prev reaches it in one step: O(1). In an array, inserting at the front requires shifting: O(n).
Short Answer · Singly Linked: Traversal and Insertion
Question 5: A Faulty Print Method
With the list 3 → 6 → 9, this method is called twice in a row. What is the output, and how do you fix the bug?
void printList() { System.out.print("Linked List: "); while (head != null) { System.out.print(head.data + " -> "); head = head.next; } System.out.println("null"); }
Show answer
Call 1: Linked List: 3 -> 6 -> 9 -> null
Call 2: Linked List: null
The loop advances head itself, so head == null at the end. The only reference to the list is gone, the nodes are unreachable (the GC reclaims them), and the list is effectively deleted.
Fix: traverse with a local pointer; head never changes:
Node temp = head; while (temp != null) { ... temp = temp.next; }
Multiple Choice · Singly Linked: Traversal and Insertion
Question 6: A Sequence of Operations
Starting from an empty singly linked list, we apply addFirst(3), addFirst(5), addLast(7), addFirst(9) in that order. What is the resulting list?
States: 3 → (5 → 3) → (5 → 3 → 7) → 9 → 5 → 3 → 7. addFirst always puts the new node in front, reversing the insertion order; B misses this. addFirst is two assignments, O(1); without a tail pointer, addLast walks to the end, O(n).
Short Answer · Singly Linked: Traversal and Insertion
Question 7: The addLast Method
This method appends a new node to the end of a singly linked list. Fill in the blanks.
class SimpleLinkedList { Node head; void addLast(int data) { Node newNode = new Node(data); if (________) { head = newNode; return; } Node temp = head; while (________) temp = ________; ________ = newNode; } }
Show answer
if (head == null) { ... } while (temp.next != null) temp = temp.next; temp.next = newNode;
If the list is empty, the new node becomes the head. Otherwise temp stops at the last node (the one whose next is null), and the new node is linked after it: O(n).
Short Answer · Singly Linked: Traversal and Insertion
Question 8: The Tail Pointer Bug
On an empty list that keeps head and tail, we call addLast(5); addLast(7);. What happens? Fix the bug.
void addLast(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; } else { tail.next = newNode; tail = newNode; } }
Show answer
Call 1: the list is empty → head = 5, but tail is still null.
Call 2: head != null → else branch → tail.next dereferences null → NullPointerException.
Fix: in the empty-list branch, head = tail = newNode;
A tail pointer makes inserting at the tail a walk-free, two-assignment O(1) operation; the price is that every operation (inserting into an empty list, deleting the last node) must keep tail current.
Multiple Choice · Singly Linked: Traversal and Insertion
Question 9: Linking Order
The last two lines of addAt have been swapped, as shown. What happens after addAt(5, 2) on the list 10 → 1 → 8 → 11?
Node temp = head; for (int i = 0; i < index - 1 && temp != null; i++) temp = temp.next; Node newNode = new Node(data); temp.next = newNode; // (2) first newNode.next = temp.next; // (1) second
With (2) first, temp.next is already 5, so (1) sets 5.next = 5. The only reference to 8 is lost and a traversal never ends. B is the distractor, but 5's next is 5 itself, not null. Correct order: link the new node to the rest of the list (1), then the previous node to the new one (2).
Short Answer · Singly Linked: Traversal and Insertion
Question 10: A Faulty addFirst
The list is 10 -> 20 -> null. A student wrote addFirst(5) as shown below. What does the list become after the method runs?
void addFirst(int data) { Node newNode = new Node(data); head = newNode; newNode.next = head; }
Show answer
List: 5 -> 5 -> 5 -> …
head = newNoderuns first, so the only reference to the old head (10) is lost; 10 and 20 become unreachable.newNode.next = headlinks the node to itself; printing loops forever.- The correct order: first
newNode.next = head;, thenhead = newNode;.
Short Answer · Singly Linked: Traversal and Insertion
Question 11: Inserting into a Linked List Incorrectly
The list is 7 → 2 → 9, and prev is the node holding 7. This code is meant to insert 4 between 7 and 2. What does it do, and how do you fix it?
Node newNode = new Node(4);
prev.next = newNode;
newNode.next = prev.next;
Show answer
After the second line prev.next is newNode, so the third sets newNode.next = newNode: the node points to itself. The only reference to 2 is lost; 2 and 9 drop out (the GC reclaims them). A traversal runs 7 → 4 → 4 → … in an infinite loop.
Fix: order matters; link the new node first, then change the previous one:
newNode.next = prev.next; // 4 → 2 prev.next = newNode; // 7 → 4
Only 2 links change and nothing shifts → O(1); but getting to the insertion point takes an O(n) walk.
Multiple Choice · Singly Linked: Deletion and Other Operations
Question 12: Deleting at the Tail with One Node
The single-node check has been removed from the singly linked removeLast. What does a call do when the list holds only 7?
void removeLast() { if (head == null) return; Node temp = head; while (temp.next.next != null) temp = temp.next; temp.next = null; tail = temp; size--; }
With one node, temp.next == null, so temp.next.next reads a field of null → NPE. Hence the branch if (head.next == null) { head = tail = null; } in the real code. With several nodes we walk to the second-to-last node: O(n), even with a tail pointer, since we cannot step back.
Short Answer · Singly Linked: Deletion and Other Operations
Question 13: Deleting a Given Item
The list is 4 → 8 → 4 → 6 (size 4). We call remove(4), remove(6), remove(5) in that order. What are the list, tail, and size at the end, and what is printed to the console?
void remove(int key) { if (head == null) return; if (head.data == key) { head = head.next; size--; if (head == null) tail = null; return; } Node prev = head, temp = head.next; while (temp != null) { if (temp.data == key) { prev.next = temp.next; if (temp == tail) tail = prev; size--; return; } prev = temp; temp = temp.next; } System.out.println("Not found."); }
Show answer
| Call | What happens | Result |
|---|---|---|
| remove(4) | removing the head: head = 8 | 8 → 4 → 6 |
| remove(6) | prev = 4, temp = 6 = tail → tail = 4 | 8 → 4 |
| remove(5) | temp becomes null | Not found. |
Result: 8 → 4, tail = 4, size = 2; console: Not found.
Only the first 4 is removed. Two pointers walk together because deleting means changing the previous node's link. Search O(n) + relinking O(1) → O(n).
Short Answer · Singly Linked: Deletion and Other Operations
Question 14: Skipping a Node
The list is 3 -> 5 -> 7 -> null. What is the list after the line below runs?
head.next = head.next.next;
Show answer
List: 3 -> 7 -> null
head.next.next is 7, so 3's link now leads to 7 and 5 is skipped. With no references left, the node holding 5 is reclaimed by the garbage collector.
Code Trace · Singly Linked: Deletion and Other Operations
Question 15: Reversing a List
The list is head → 1 → 2 → 3 → null. When the code finishes, which node does head point to, and what does each node's next field point to?
Start: each node's next field points to the node on its right; 3's points to null.
prev is null; current is at the first node.
current is not null → enter the loop.
Save the next node (2) before cutting the link.
1.next = prev: 1 now points to null (orange). The variable next still reaches 2.
prev and current each move one node forward.
Round 2: 2.next = 1 (orange link); both pointers again move one node.
Round 3: 3.next = 2; current becomes null.
current == null → the loop ends. head still points to 1.
head = prev: the list is 3 → 2 → 1 → null. No new nodes; O(n) time, O(1) extra space.
Node prev = null, current = head; while (current != null) { Node next = current.next; current.next = prev; prev = current; current = next; } head = prev;
Multiple Choice · Singly Linked: Deletion and Other Operations
Question 16: The Middle Item
What does findMiddle() return for the list 2 → 4 → 6 → 8 → 10 → 12?
int findMiddle() { if (head == null) throw new IllegalStateException( "List is empty"); Node slow = head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; // 1 step fast = fast.next.next; // 2 steps } return slow.data; }
Rounds (slow, fast): (4, 6), (6, 10), (8, null). After round 2, fast.next = 12 is not null, so a third round runs; an even length yields the second middle. 6 (the first middle) is the strongest distractor. One pass, length unknown: O(n).
Code Trace · Singly Linked: Deletion and Other Operations
Question 17: Merging Sorted Lists
l1 = 2 → 5 → 9, l2 = 3 → 4; result is empty and addLast is O(1). How many comparisons does the main loop make, and what is result?
The two pointers start at the heads of the two sorted lists.
Neither list is exhausted; 2 ≤ 3 → true.
Append 2; p1 advances.
5 ≤ 3 → false: l2 has the smaller value.
Append 3; p2 advances.
5 ≤ 4 → false.
Append 4; p2 is now null.
p2 == null → the main loop ends: 3 comparisons.
What is left in l1 is appended without comparisons: 5.
Append 9; p1 is null.
p2 is already null, so its loop doesn't run. Result: 2 → 3 → 4 → 5 → 9. Each item is appended once: O(n + m) (with addLast in O(1)).
Node p1 = l1.head, p2 = l2.head; while (p1 != null && p2 != null) { if (p1.data <= p2.data) { result.addLast(p1.data); p1 = p1.next; } else { result.addLast(p2.data); p2 = p2.next; } } while (p1 != null) { result.addLast(p1.data); p1 = p1.next; } while (p2 != null) { result.addLast(p2.data); p2 = p2.next; }
Multiple Choice · Doubly Linked List
Question 18: Doubly Linked: Gains and Costs
Which of the following is not an advantage of a doubly linked list over a singly linked list?
On the contrary, each node carries a second reference (prev), and every insertion and deletion must update both directions: that is the price. B, C, and D are gains: tail.prev and d.prev reach the previous node in one step.
Short Answer · Doubly Linked List
Question 19: Link Order (3) ↔ (4)
The list is 1 ⇄ 10 ⇄ 15 ⇄ 25, with temp = node(10). In the doubly linked addAt, (3) and (4) have been swapped. What do forward and backward printing give, and which link is broken?
Node newNode = new Node(12); newNode.next = temp.next; // (1) newNode.prev = temp; // (2) temp.next = newNode; // (4) first temp.next.prev = newNode; // (3) second
Show answer
Forward: 1 10 12 15 25 · Backward: 25 15 10 1 (no 12).
With (4) first, temp.next is already 12, so (3), temp.next.prev = newNode, sets 12.prev = 12: the node points to itself. 15's prev still points to 10, so walking backward skips 12.
The correct order is (3), then (4): fix 15's backward link while temp.next still reaches 15. Linking is O(1); walking to the position O(n). (If temp is the tail, the real code calls addLast, which also updates tail.)
Code Trace · Circularly Linked List
Question 20: Detecting a Cycle with Floyd's Algorithm
The list is 1 → 2 → 3 → 4 → 5, and 5 points back to 2 (the cycle does not return to the head). In which round, and at which node, does hasCycle(head) return true?
Both pointers start at the head.
Round 1: fast (1) and fast.next (2) are not null.
slow moves 1 step, fast 2.
2 ≠ 3 → continue.
Round 2: slow moves to 3, fast to 5.
3 ≠ 5 → continue.
Round 3: fast goes 5 → 2 → 3; it has gone around the cycle and is coming up behind slow.
4 ≠ 3 → continue.
Round 4: slow moves to 5; fast goes 3 → 4 → 5.
slow == fast (node 5) → return true. Inside the cycle, fast gains one node each round: O(n) time, O(1) space.
boolean hasCycle(Node head) { Node slow = head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) return true; } return false; }
Multiple Choice · Circularly Linked List
Question 21: A Sequence of Circular Operations
Starting from an empty circular list (only tail is kept), we apply addLast(1), addLast(8), addFirst(5), removeFirst(), addLast(10), rotate() in that order. What does print() then output?
States: [1] → [1, 8] → [5, 1, 8] (tail unchanged) → [1, 8] → [1, 8, 10], tail = 10. rotate() only does tail = tail.next: tail becomes 1, the head 8: 8 10 1. A forgets the rotate. rotate changes no links, O(1); round-robin scheduling serves the head each round, then rotates.
Short Answer · Summary
Question 22: Complexity Table
Fill in the table with O(1) / O(n) (n: number of nodes).
| Operation | Singly (head+tail) | Doubly (head+tail) | Circular singly (tail only) |
|---|---|---|---|
| Insert at the tail | ? | ? | ? |
| Delete at the tail | ? | ? | ? |
| Delete a known node | ? | ? | ? |
| Access the i-th item | ? | ? | ? |
Show answer
| Operation | Singly (head+tail) | Doubly (head+tail) | Circular singly (tail only) |
|---|---|---|---|
| Insert at the tail | O(1) | O(1) | O(1) |
| Delete at the tail | O(n) | O(1) | O(n) |
| Delete a known node | O(n) | O(1) | O(n) |
| Access the i-th item | O(n) | O(n) | O(n) |
In the singly linked and circular lists, deleting at the tail or a known node means finding the previous node: an O(n) walk. The doubly linked list's prev field makes it O(1). Inserting and deleting at the front are O(1) in all three; in an array, inserting at the front is O(n) and the i-th item O(1).
Open-Ended Question · Summary
Question 23: A Music Playlist
Design a music player's playlist with next/previous song, wrap-around from the end to the start (repeat mode), and deletion of the current song. Which kind of linked list and which pointers would you use, and what would each operation cost?
Sample answer
A doubly linked circular list plus a current pointer (and tail for appending; head = tail.next).
- Next/previous:
current.next/current.prev→ O(1); wrapping from the end to the start comes for free with the ring (no null checks). - Deleting the playing song:
d.prev.next = d.next; d.next.prev = d.prev;→ O(1); if it was the tail, updatetail, and if it was the only song, the list becomes empty. - Appending a song is O(1); searching by title is O(n).
A singly linked circular list would make "previous" and deletion O(n). A circular traversal must stop on returning to the start, not on != null.
Multiple Choice · Doubly Linked List
Question 24: A Sequence of Operations with Sentinels
We start with an empty list from the sentinel version in the slides (addBetween, addFirst, remove). After these calls, what are the real items from head to tail, and what is size?
// initially: header ⇄ trailer
addFirst(4);
addFirst(9);
Node a = header.next;
addBetween(6, a, a.next);
remove(trailer.prev);addFirst(4): pred = header, succ = trailer; even an empty list has both neighbors and no null (D is wrong). addFirst(9) puts 9 in front: 9 ⇄ 4. a = 9; 6 goes between 9 and 4: 9 ⇄ 6 ⇄ 4. trailer.prev = 4 is removed → 9 ⇄ 6, size 2. A treats addFirst as inserting at the tail; C puts 6 after a.next.
Short Answer · Doubly Linked List
Question 25: Deleting the Only Node, with and without Sentinels
Each of two lists holds a single real node, 7. On the doubly linked list without sentinels we call remove(7); on the one with sentinels, remove(d) (d = node(7)). Which assignments happen in each, and what do head/tail or the sentinels point to at the end? Why is there no if in the sentinel version?
// with sentinels void remove(Node d) { d.prev.next = d.next; d.next.prev = d.prev; size--; }
Show answer
Without sentinels: temp.prev == null → head = temp.next = null; temp.next == null → tail = temp.prev = null. Both special cases (deleting the head and deleting the tail) fire at once.
With sentinels: header.next = trailer, trailer.prev = header, size = 0: the empty-list picture.
Every real node always has two neighbors (a sentinel if need be): no null checks and no head/tail updates. The price: two extra nodes. Relinking is O(1) in both.
Short Answer · Singly Linked: Deletion and Other Operations
Question 26: Deep Copy or Alias?
What are the lists a, b, and c at the end of the code? What would change if copy() did only newList.head = head instead of creating new nodes?
SinglyLinkedList a =
new SinglyLinkedList();
a.addLast(3); a.addLast(5); a.addLast(7);
SinglyLinkedList b = a;
SinglyLinkedList c = a.copy();
b.addFirst(1);
c.remove(5);
a.addLast(9);
Show answer
b = acopies only the reference: two names for the same object (aliasing) → a = b = 1 → 3 → 5 → 7 → 9.copy()makes a deep copy: new nodes for 3, 5, 7. c.remove(5) changes only c → c = 3 → 7.- newList.head = head: c is a separate object sharing the same nodes as a. c.remove(5) points 3's link to 7, so 5 vanishes from a too: a = 1 → 3 → 7 → 9, and c sees 3 → 7 → 9 (size and tail go out of sync as well).
Multiple Choice · Singly Linked: Deletion and Other Operations
Question 27: The k-th Item from the End
What does kthFromEnd(2) return for the list 3 → 6 → 9 → 12 → 15 → 18?
int kthFromEnd(int k) { // k ≥ 1 Node fast = head, slow = head; for (int i = 0; i < k; i++) fast = fast.next; // k steps ahead while (fast != null) { slow = slow.next; fast = fast.next; } return slow.data; }
After the for loop, fast = 9 (2 steps ahead). Together (slow, fast): (6, 12), (9, 15), (12, 18), (15, null) → 15. The gap stays k: one pass, length unknown, O(n). B is fast's position after the for loop; A and D come from k + 1 and k − 1 steps of lead. If k exceeds the length, the for loop throws a NullPointerException.