Chapter 5: Linked Lists
Introduction
Learning Outcomes
Explain nodes, links, and references.
Implement insertion, deletion, search, and traversal.
Compare singly, doubly, and circularly linked lists.
Evaluate the time and space costs of linked-list operations.
Basics
Kinds of Linked Lists
null.null, closing the list into a ring.In all three, items live not in adjacent cells, as in an array, but in nodes that point to one another.
Basics
Singly Linked List
- Items are connected by one-way links: each item holds a reference to the one after it.
- The list keeps a special reference to the first item, called the head (
headin code). - Each node has two parts:
- Data: the value the node carries (a primitive or an object).
- Link (pointer): a reference to the next node;
nullin the last node.
Basics
Where Do Nodes Live in Memory?
- Items are not stored contiguously; each node is created separately with
new. - Still, the list is a linear structure: every node except the last has exactly one successor.
- The order comes from the references in the next fields, not from memory addresses.
The list order is 10 → 1 → 8 → 11, but the nodes sit in memory in a different order; the arrows follow the references.
Basics
The Node Class
// Node class class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } }
// Node class class Node<T> { T data; Node<T> next; Node(T data) { this.data = data; this.next = null; } }
- The class has a field of its own type (
Node next): a self-referential structure. - The generic version stores any type:
Node<String> d = new Node<>("Ann"); - A new node's
nextfield starts asnulland changes once the node is linked into a list.
Basics · Step through the code
Building a Singly Linked List
new Node(10): creates a node with data = 10 and next = null; first points to it.
The second node (1) is created. The nodes are not linked yet.
The third node (8) is created. Each node can sit anywhere in memory.
The fourth node (11) is created. We have four separate nodes, each with a next field of null (⁄).
first.next = second: the next field of 10 now points to 1 (orange).
second.next = third: links 1 → 8.
third.next = fourth: the list is ready: 10 → 1 → 8 → 11 → null. first alone is enough to reach the whole list.
Node first = new Node(10); Node second = new Node(1); Node third = new Node(8); Node fourth = new Node(11); first.next = second; second.next = third; third.next = fourth;
Basics
Singly Linked List Operations
| Operation | How it works | Cost |
|---|---|---|
| Insert at head | New node points to the old head; head becomes the new node | O(1) |
| Insert at tail | Walk to the last node (no walk with a tail pointer) | O(n) · O(1) |
| Delete at head | Move head to the next node | O(1) |
| Delete at tail | Must find the second-to-last node | O(n) |
| Search · print · length | Walk from head to tail | O(n) |
| Reverse · merge | One pass over the lists (merge needs a tail pointer) | O(n) |
n: number of nodes. Reaching the i-th item is also O(n): unlike an array, we cannot jump to an index.
Basics
The Singly Linked List ADT and Its Java Class
public class SinglyLinkedList { private Node head = null, tail = null; private int size = 0; // number of items public int size() { return size; } public boolean isEmpty() { return size == 0; } public Integer first() { return isEmpty() ? null : head.data; } // addFirst, addLast, removeFirst … }
| Goodrich–Tamassia | In these slides | Purpose | Cost |
|---|---|---|---|
size(), isEmpty() | size(), isEmpty() | the size field is updated by every operation | O(1) |
first(), last() | first(), isEmpty() ? null : tail.data | return null on an empty list | O(1) |
addFirst, addLast | addFirst, addLast | both constant time with a tail pointer; inserting into an empty list also sets tail | O(1) |
removeFirst() | removeFirst() | returns the removed node | O(1) |
Basics
Singly Linked Lists: Pros and Cons
Advantages
- Easy to implement.
- Insert / delete at the head in O(1); inserting in the middle needs no shifting.
- Dynamic size: no capacity reserved in advance; the item count can change freely.
Disadvantages
- Search is slow: O(n).
- No random access; reaching the i-th item means walking from the head.
- Each node carries an extra reference (more memory).
- Cannot be traversed backward.
Singly Linked: Traversal and Insertion · Step through the code
Traversing and Printing a List
temp = head: the walk starts at the head. head never changes; only temp moves.
Print the heading.
temp != null (node 10) → enter the loop body.
Print temp.data = 10.
temp = temp.next → temp is now node(1).
temp = node(1) ≠ null → continue.
Print temp.data = 1.
temp = temp.next → temp is now node(8).
temp = node(8) ≠ null → continue.
Print temp.data = 8.
temp = temp.next → temp is now node(11).
temp = node(11) ≠ null → continue.
Print temp.data = 11.
temp = temp.next → temp is now null (the last node's next field).
temp == null → the condition is false and the loop ends.
Print null at the end. For n nodes the loop runs n times: O(n).
void printList() { Node temp = head; System.out.print("Linked List: "); while (temp != null) { System.out.print(temp.data + " -> "); temp = temp.next; } System.out.println("null"); }
Singly Linked: Traversal and Insertion
Same Pattern: Length and Search
int listLength() { int length = 0; Node temp = head; while (temp != null) { length++; temp = temp.next; } return length; }
int search(int target) { Node temp = head; int position = 0; while (temp != null) { if (temp.data == target) return position; position++; temp = temp.next; } return -1; // not found }
temp = head, do the work while temp != null, and advance with temp = temp.next. If the length is needed often, keep a size field and update it on every insertion and deletion; the length then costs O(1).Singly Linked: Traversal and Insertion · Step through the code
Code Trace: search(8)
search(8): start at the head with temp = head.
position = 0: counts temp's place (index) in the list.
temp = node(10) ≠ null → loop.
10 == 8? No → continue.
position++ → 1.
temp = temp.next → node(1).
temp = node(1) ≠ null → loop.
1 == 8? No → continue.
position++ → 2.
temp = temp.next → node(8).
temp = node(8) ≠ null → loop.
8 == 8 → found the target.
return 2. We looked at 3 nodes; in the worst case (target absent) we look at all n: O(n), result −1.
int search(int target) { Node temp = head; int position = 0; while (temp != null) { if (temp.data == target) return position; position++; temp = temp.next; } return -1; // not found }
Singly Linked: Traversal and Insertion · Step through the code
Inserting at the Head — O(1)
Call addFirst(11). The list is empty: head = null.
Create node 11; its next is null.
newNode.next = head: head is null, so 11's next stays null.
head = newNode: head moves to 11: 11 → null.
if (tail == null) tail = head: the list was empty, so 11 is both head and tail. size++ → 1.
Call addFirst(8). List: 11 → null.
Create node 8; its next is null.
newNode.next = head: 8 points to the old head (11). Changing head first would lose 11.
head = newNode: head moves to 8: 8 → 11 → null.
tail is not null, so it stays at 11. size++ → 2.
Call addFirst(1). List: 8 → 11 → null.
Create node 1; its next is null.
newNode.next = head: 1 points to the old head (8). Changing head first would lose 8.
head = newNode: head moves to 1: 1 → 8 → 11 → null.
tail stays at 11. size++ → 3. However long the list, a fixed number of assignments: O(1).
void addFirst(int data) { Node newNode = new Node(data); newNode.next = head; head = newNode; if (tail == null) tail = head; size++; }
Singly Linked: Traversal and Insertion · Step through the code
Inserting at the Tail — O(n)
addLast(10): create the new node.
head == null → the list is empty.
head = newNode: a one-node list.
return: no walk needed.
addLast(1): create the new node.
The list is not empty → walk to the end.
temp = head: start at the head to find the last node.
node(10).next == null → temp is at the last node; the loop ends.
temp.next = newNode: 10 → 1 → null.
addLast(8): create the new node.
The list is not empty → walk to the end.
temp = head: start at the head to find the last node.
node(10).next is not null → advance.
temp = temp.next → node(1).
node(1).next == null → temp is at the last node; the loop ends.
temp.next = newNode: 10 → 1 → 8 → null. Every insertion walks to the end: O(n).
void addLast(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; return; } Node temp = head; while (temp.next != null) temp = temp.next; temp.next = newNode; }
Singly Linked: Traversal and Insertion
Inserting at the Tail with a Tail Pointer — O(1)
class SinglyLinkedList { Node head, tail; int size; void addLast(int data) { Node newNode = new Node(data); if (head == null) { head = tail = newNode; } else { tail.next = newNode; tail = newNode; } size++; } }
tail up to date (inserting into an empty list, deleting the last node).tail.Singly Linked: Traversal and Insertion · Step through the code
Code Trace: addLast with tail
addLast(10): create the new node.
head == null → the list is empty.
head = tail = newNode: the single node is both head and tail.
size++ → 1.
addLast(1): create the new node.
The list is not empty; the last node is already known: node(10).
tail.next = newNode: links 10 → 1. No walk.
tail = newNode: tail is now 1.
size++ → 2.
addLast(8): create the new node.
The list is not empty; the last node is already known: node(1).
tail.next = newNode: links 1 → 8. No walk.
tail = newNode: tail is now 8.
size++ → 3. Each call makes a fixed number of assignments: O(1).
void addLast(int data) { Node newNode = new Node(data); if (head == null) { head = tail = newNode; } else { tail.next = newNode; tail = newNode; } size++; }
Singly Linked: Traversal and Insertion
Inserting at a Given Position
void addAt(int data, int index) { // index starts at 0 if (index == 0) { addFirst(data); return; } Node temp = head; for (int i = 0; i < index - 1 && temp != null; i++) temp = temp.next; if (temp == null) { // list shorter than index System.out.println("Position not found."); return; } Node newNode = new Node(data); newNode.next = temp.next; // (1) temp.next = newNode; // (2) if (temp == tail) tail = newNode; // inserted at the end size++; }
Singly Linked: Traversal and Insertion · Step through the code
Code Trace: addAt(5, 2)
addAt(5, 2): index ≠ 0, so this is not an insert at the head. temp = head; we advance index − 1 = 1 step.
i = 0: 0 < 1 and temp != null → loop body.
temp = temp.next → node(1).
i = 1: 1 < 1 is false → the loop ends. temp is at the node with index 1 (just before the insertion point).
temp is not null → the position is valid; no error message.
Create the new node (5). (The drawing shifts 8 and 11 to the right; nothing moves in memory.) 1 still points to 8.
(1) newNode.next = temp.next: 5 points to 8. The list has not changed yet.
(2) temp.next = newNode: 10 → 1 → 5 → 8 → 11. Only 2 links changed; in the reverse order the path to 8 would be lost.
Node temp = head; for (int i = 0; i < index - 1 && temp != null; i++) temp = temp.next; if (temp == null) { // list shorter than index System.out.println("Position not found."); return; } Node newNode = new Node(data); newNode.next = temp.next; // (1) temp.next = newNode; // (2)
Singly Linked: Deletion and Other Operations · Step through the code
Deleting at the Head — O(1)
Call 1: head is not null (10 → 1 → 11 → null).
temp = head: save the node being removed (10).
head = head.next: head is node(1); 10 is now unreachable.
temp.next = null: 10 is fully detached.
return temp: 10 goes back to the caller. Once unreferenced, it is reclaimed by the GC. O(1).
Call 2: head is not null (1 → 11 → null).
temp = head: save the node being removed (1).
head = head.next: head is node(11); 1 is now unreachable.
temp.next = null: 1 is fully detached.
return temp: 1 goes back to the caller. Once unreferenced, it is reclaimed by the GC. O(1).
Call 3: head is not null (11 → null).
temp = head: save the node being removed (11).
head = head.next: head is null and the list is empty; 11 is now unreachable.
temp.next = null: 11 is fully detached.
return temp: 11 goes back to the caller. Once unreferenced, it is reclaimed by the GC. O(1).
On an empty list, head == null → return null. Without this check, head.next would throw a NullPointerException.
Node removeFirst() {
if (head == null)
return null;
Node temp = head;
head = head.next; if (head == null) tail = null;
temp.next = null; size--;
return temp;
}
Singly Linked: Deletion and Other Operations · Step through the code
Deleting at the Tail — O(n)
The list is not empty.
head.next is not null → there is more than one node.
temp = head. Goal: find the second-to-last node (its link will change).
node(10).next.next = 8 ≠ null → advance.
temp = temp.next → node(1).
node(1).next.next = 11 ≠ null → advance.
temp = temp.next → node(8).
node(8).next.next == null → temp is at the second-to-last node.
temp.next = null: 11 leaves the list → 10 → 1 → 8 → null. O(n); a tail pointer doesn't help, because we cannot step back.
void removeLast() { if (head == null) return; if (head.next == null) { // single node head = tail = null; size--; return; } Node temp = head; while (temp.next.next != null) temp = temp.next; temp.next = null; tail = temp; size--; }
Singly Linked: Deletion and Other Operations
Deleting a Given Item
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; Node 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."); }
prev.next = temp.next
the doomed node is "skipped"
- Two pointers walk together: deleting needs the previous node.
- Deleting the head is a separate case.
- Search O(n) + relinking O(1) → O(n).
Singly Linked: Deletion and Other Operations · Step through the code
Code Trace: remove(8)
remove(8): the list is not empty and the head 10 ≠ 8 (both ifs passed). prev = head.
temp = head.next: the two pointers walk side by side; deleting needs the previous node.
temp = node(1) is not null → loop.
1 == 8? No.
prev = temp → node(1).
temp = temp.next → node(8).
temp = node(8) is not null → loop.
8 == 8 → found the node to delete.
prev.next = temp.next: 1 now points to 11; 8 is "skipped".
return. List: 10 → 1 → 11 → null. Search O(n) + relinking O(1) → O(n).
Node prev = head; Node 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.");
Singly Linked: Deletion and Other Operations
Reversing a List
void reverse() { tail = head; // old head becomes the new tail Node prev = null; Node current = head; Node next = null; while (current != null) { next = current.next; // 1) save next current.next = prev; // 2) reverse the link prev = current; // 3) advance prev current = next; // 4) advance current } head = prev; }
Singly Linked: Deletion and Other Operations · Step through the code
Code Trace: reverse()
Start: prev = null, current = head (10), next = null. No new nodes will be created.
Round 1: current = node(10) is not null.
1) next = current.next = node(8): so the rest of the list survives the cut.
2) current.next = prev: 10 now points to null (link reversed).
3–4) prev = current; current = next: both pointers move one node forward.
Round 2: current = node(8) is not null.
1) next = current.next = node(1): so the rest of the list survives the cut.
2) current.next = prev: 8 now points to node(10) (link reversed).
3–4) prev = current; current = next: both pointers move one node forward.
Round 3: current = node(1) is not null.
1) next = current.next = node(11): so the rest of the list survives the cut.
2) current.next = prev: 1 now points to node(8) (link reversed).
3–4) prev = current; current = next: both pointers move one node forward.
Round 4: current = node(11) is not null.
1) next = current.next = null: so the rest of the list survives the cut.
2) current.next = prev: 11 now points to node(1) (link reversed).
3–4) prev = current; current = next: both pointers move one node forward.
current == null → the loop ends; prev is at the old last node (11).
head = prev: the new list is 11 → 1 → 8 → 10 → null. O(n) time, O(1) extra space.
tail = head; // old head becomes the new tail Node prev = null; Node current = head; Node next = null; while (current != null) { next = current.next; // 1) save next current.next = prev; // 2) reverse the link prev = current; // 3) advance prev current = next; // 4) advance current } head = prev;
Singly Linked: Deletion and Other Operations · Step through the code
Finding the Middle: Slow and Fast Pointers
The list is not empty (an empty list throws an exception).
Both pointers start at the head. We find the middle without knowing the length.
fast = node(10) and fast.next = node(8) are not null → round 1.
slow moves 1 step → node(8).
fast moves 2 steps → node(1).
fast = node(1) and fast.next = node(11) are not null → round 2.
slow moves 1 step → node(1).
fast moves 2 steps → node(5).
fast.next == null → fast has reached the end; the loop ends. In 2 rounds slow took 2 steps and fast took 4.
return 1: the slow pointer is in the middle. One pass, O(n). For an even length it returns the second middle (10, 8, 1, 11 → 1).
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; }
Singly Linked: Deletion and Other Operations
Copying a List
SinglyLinkedList copy() {
SinglyLinkedList newList =
new SinglyLinkedList();
Node temp = head;
while (temp != null) {
newList.addLast(temp.data);
temp = temp.next;
}
return newList;
}
newList.head = head would only give a second reference to the same list.addLast walks to the end every time, the total is O(n²); with a tail pointer, O(n).Singly Linked: Deletion and Other Operations · Step through the code
Code Trace: copy()
Create a new, empty list. Writing newList.head = head would not be a copy, just a second reference to the same nodes.
temp = head: walk the original list from the head.
temp = node(10) is not null.
newList.addLast(10): a new node goes on the end of the copy.
temp = temp.next → node(1).
temp = node(1) is not null.
newList.addLast(1): a new node goes on the end of the copy.
temp = temp.next → node(8).
temp = node(8) is not null.
newList.addLast(8): a new node goes on the end of the copy.
temp = temp.next → null.
temp == null → the loop ends.
return newList: the same values in different nodes (a deep copy). If addLast is O(n) the total is O(n²); with a tail pointer, O(n).
SinglyLinkedList copy() {
SinglyLinkedList newList =
new SinglyLinkedList();
Node temp = head;
while (temp != null) {
newList.addLast(temp.data);
temp = temp.next;
}
return newList;
}
Singly Linked: Deletion and Other Operations
Removing Duplicates from a List
void removeDuplicates() { SinglyLinkedList seen = new SinglyLinkedList(); Node prev = null, temp = head; while (temp != null) { int v = temp.data; if (seen.contains(v)) { prev.next = temp.next; // skip if (temp == tail) tail = prev; size--; } else { seen.addFirst(v); prev = temp; } temp = temp.next; } }
seen list for every node: O(n²). With a hash set, O(n).prev is null.contains(v): search(v) != -1. Example: 3 → 5 → 3 → 7 → 5 ⇒ 3 → 5 → 7
Singly Linked: Deletion and Other Operations · Step through the code
Code Trace: Removing Duplicates (3, 5, 3, 7, 5)
Start (earlier lines): seen is empty, prev = null, temp = head. temp = node(3) is not null.
v = 3.
seen.contains(3) → false: 3 is new.
seen.addFirst(3); prev = temp: the node stays; prev moves to it.
temp = temp.next → node(5).
temp = node(5) is not null.
v = 5.
seen.contains(5) → false: 5 is new.
seen.addFirst(5); prev = temp: the node stays; prev moves to it.
temp = temp.next → node(3).
temp = node(3) is not null.
v = 3.
seen.contains(3) → true: 3 was seen before; this node is a duplicate.
prev.next = temp.next: 5 → node(7); the duplicate 3 is skipped. prev stays put.
temp = temp.next → node(7).
while (temp != null) { int v = temp.data; if (seen.contains(v)) { prev.next = temp.next; // skip if (temp == tail) tail = prev; size--; } else { seen.addFirst(v); prev = temp; } temp = temp.next; }
Singly Linked: Deletion and Other Operations · Step through the code
Code Trace: Removing Duplicates (continued)
temp = node(7) is not null.
v = 7.
seen.contains(7) → false: 7 is new.
seen.addFirst(7); prev = temp: the node stays; prev moves to it.
temp = temp.next → node(5).
temp = node(5) is not null.
v = 5.
seen.contains(5) → true: 5 was seen before; this node is a duplicate.
prev.next = temp.next: 7 → null; the duplicate 5 is skipped. prev stays put.
temp = temp.next → null.
temp == null → the loop ends. Result: 3 → 5 → 7 → null. A search in seen for every node: O(n²); with a hash set, O(n).
while (temp != null) { int v = temp.data; if (seen.contains(v)) { prev.next = temp.next; // skip if (temp == tail) tail = prev; size--; } else { seen.addFirst(v); prev = temp; } temp = temp.next; }
Singly Linked: Deletion and Other Operations
Merging Two Sorted Lists
SinglyLinkedList merge(
SinglyLinkedList l1,
SinglyLinkedList l2) {
SinglyLinkedList result =
new SinglyLinkedList();
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;
}
}
// append the leftovers while (p1 != null) { result.addLast(p1.data); p1 = p1.next; } while (p2 != null) { result.addLast(p2.data); p2 = p2.next; } return result; }
⇒ 1 → 2 → 3 → 4 → 7 → 8
If addLast is O(1) (tail pointer), the total is O(n + m) (n, m: list lengths); if each insertion walks to the end, O((n + m)²).
Singly Linked: Deletion and Other Operations · Step through the code
Code Trace: merge (1, 4, 7 + 2, 3, 8)
result is a new, empty list. p1 and p2 start at the heads of the two sorted lists.
Neither list is exhausted → compare.
1 ≤ 2 → true: l1 has the smaller value.
Append 1; p1 advances.
Neither list is exhausted → compare.
4 ≤ 2 → false: l2 has the smaller value.
Append 2; p2 advances.
Neither list is exhausted → compare.
4 ≤ 3 → false: l2 has the smaller value.
Append 3; p2 advances.
Neither list is exhausted → compare.
4 ≤ 8 → true: l1 has the smaller value.
Append 4; p1 advances.
Neither list is exhausted → compare.
7 ≤ 8 → true: l1 has the smaller value.
Append 7; p1 advances.
p1 == null: l1 is exhausted → the main loop ends. What is left in l2 (8) is already sorted.
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; } }
Singly Linked: Deletion and Other Operations · Step through the code
Code Trace: merge (continued)
Leftovers: p1 == null → the first loop never runs.
p2 = node(8) is not null.
Append 8; p2 advances.
p2 == null → done.
return result: 1 → 2 → 3 → 4 → 7 → 8. If addLast is O(1) (tail pointer), the total is O(n + m).
// append the leftovers while (p1 != null) { result.addLast(p1.data); p1 = p1.next; } while (p2 != null) { result.addLast(p2.data); p2 = p2.next; } return result;
Singly Linked: Deletion and Other Operations
Sorting a Singly Linked List
void sort() { Node current = head; while (current != null) { Node other = current.next; while (other != null) { if (current.data > other.data) { int temp = current.data; current.data = other.data; other.data = temp; } other = other.next; } current = current.next; } }
data fields change.Singly Linked: Deletion and Other Operations · Step through the code
Code Trace: sort() (4 → 1 → 3 → 2)
List 4 → 1 → 3 → 2. current starts at the head; the nodes stay in place and only the data fields change.
other = current.next → node(1). current (4) is compared with each later node.
4 > 1 → swap the values (temp = 4). List: 1 → 4 → 3 → 2.
1 > 3? No → no swap; other advances.
1 > 2? No → no swap; other advances.
The inner loop is done: the smallest remaining value is now in current's node. current advances → node(4).
other = current.next → node(3). current (4) is compared with each later node.
4 > 3 → swap the values (temp = 4). List: 1 → 3 → 4 → 2.
3 > 2 → swap the values (temp = 3). List: 1 → 2 → 4 → 3.
The inner loop is done: the smallest remaining value is now in current's node. current advances → node(4).
other = current.next → node(3). current (4) is compared with each later node.
4 > 3 → swap the values (temp = 4). List: 1 → 2 → 3 → 4.
The inner loop is done: the smallest remaining value is now in current's node. current advances → node(4).
other = current.next = null: there is nothing left to compare the last node with.
current = null → the outer loop ends. Result: 1 → 2 → 3 → 4; 6 comparisons = n(n−1)/2, 4 swaps.
void sort() { Node current = head; while (current != null) { Node other = current.next; while (other != null) { if (current.data > other.data) { int temp = current.data; current.data = other.data; other.data = temp; } other = other.next; } current = current.next; } }
Doubly Linked List
Doubly Linked List
- A structure whose nodes are linked in both directions.
- Each node holds two pointers: one to the previous node and one to the next.
- The list can be walked either way; usually both a head (
head) and a tail (tail) are kept.
Doubly Linked List
Doubly Linked List: Node and Structure
class Node { int data; Node prev; Node next; Node(int data) { this.data = data; this.prev = null; this.next = null; } }
- Items can be reached going forward or backward.
- Inserting a node means updating pointers in both directions.
- Removing a node means updating the pointers of both the previous and the next node.
- A search can walk forward or backward.
- The list keeps the fields
Node head, tail;.
Doubly Linked List · Step through the code
Inserting at the Head of a Doubly Linked List — O(1)
addFirst(1): the new node's prev and next fields are null (⁄).
head is not null → else branch.
newNode.next = head: forward link 1 → 10.
head.prev = newNode: backward link 10 → 1 (10's null is gone).
head = newNode: 1 ⇄ 10 ⇄ 15 ⇄ 25. O(1). Had the list been empty, head and tail would both become the new node.
public void addFirst(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; tail = newNode; } else { newNode.next = head; head.prev = newNode; head = newNode; } }
Doubly Linked List · Step through the code
Inserting at the Tail of a Doubly Linked List — O(1)
addLast(30): create the new node.
The list is not empty → else. tail gives the last node directly.
newNode.prev = tail: backward link 30 → 25.
tail.next = newNode: forward link 25 → 30.
tail = newNode: 1 ⇄ 10 ⇄ 15 ⇄ 25 ⇄ 30. No walk: O(1).
public void addLast(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; tail = newNode; } else { newNode.prev = tail; tail.next = newNode; tail = newNode; } }
Doubly Linked List
Inserting at a Position in a Doubly Linked List
void addAt(int data, int index) { // index starts at 0 if (index == 0) { addFirst(data); return; } Node temp = head; for (int i = 0; i < index - 1 && temp != null; i++) temp = temp.next; if (temp == null) { System.out.println("Invalid position."); return; } if (temp == tail) { addLast(data); return; } // updates tail too Node newNode = new Node(data); newNode.next = temp.next; // (1) newNode.prev = temp; // (2) temp.next.prev = newNode; // (3) temp.next = newNode; // (4) }
Doubly Linked List · Step through the code
Code Trace: addAt(12, 2) — the linking part
addAt(12, 2): as in the singly linked version, temp has walked to the node at index − 1 = 1 (10). Create the new node.
(1) newNode.next = temp.next: 12 → 15. The list has not changed yet.
(2) newNode.prev = temp: backward link 12 → 10.
(3) temp.next.prev = newNode: 15's backward link now points to 12. This must come before (4), while temp.next is still 15.
(4) temp.next = newNode: 10 → 12. Four links changed; swapping (3) and (4) would leave 15 unreachable.
Result (drawing tidied): 1 ⇄ 10 ⇄ 12 ⇄ 15 ⇄ 25. Linking is O(1); walking to the position is O(n).
Node newNode = new Node(data); newNode.next = temp.next; // (1) newNode.prev = temp; // (2) temp.next.prev = newNode; // (3) temp.next = newNode; // (4)
Doubly Linked List
Deleting at the Head and Tail of a Doubly Linked List
void removeFirst() { if (head == null) return; // empty if (head == tail) { // single node head = tail = null; } else { head = head.next; head.prev = null; } }
void removeLast() { if (tail == null) return; // empty if (head == tail) { // single node head = tail = null; } else { tail = tail.prev; tail.next = null; } }
tail.prev; no walk is needed. In a singly linked list the same operation is O(n). When deleting the only node, set both head and tail to null.Doubly Linked List · Step through the code
Code Trace: Doubly Linked removeFirst()
List: 1 ⇄ 10 ⇄ 15. Not empty.
head != tail → several nodes, else branch.
head = head.next: head moves to 10; 1 is now unreachable.
head.prev = null: clear 10's backward link too; otherwise it would still point to the removed node. O(1).
void removeFirst() { if (head == null) return; // empty if (head == tail) { // single node head = tail = null; } else { head = head.next; head.prev = null; } }
Doubly Linked List · Step through the code
Deleting at the Tail, Step by Step
List: 1 ⇄ 10 ⇄ 15 ⇄ 25; tail points to 25.
head != tail → else branch.
tail = tail.prev: we reach the second-to-last node in one step (a singly linked list would need a walk).
tail.next = null: 25 leaves the list. Result: 1 ⇄ 10 ⇄ 15. No walk: O(1).
void removeLast() { if (tail == null) return; if (head == tail) { head = tail = null; } else { tail = tail.prev; tail.next = null; } }
Doubly Linked List
Deleting a Given Item from a Doubly Linked List
void remove(int data) { Node temp = head; while (temp != null && temp.data != data) temp = temp.next; if (temp == null) return; // not found if (temp.prev != null) temp.prev.next = temp.next; else head = temp.next; // removing the head if (temp.next != null) temp.next.prev = temp.prev; else tail = temp.prev; // removing the tail }
The removed node's neighbors are linked to each other. If the head or the tail is removed, update head/tail. Search O(n), deletion O(1).
Doubly Linked List · Step through the code
Code Trace: Doubly Linked remove(15)
remove(15): temp = head; first we search for the node to delete.
node(1) is not null and 1 ≠ 15 → advance.
temp = temp.next → node(10).
node(10) is not null and 10 ≠ 15 → advance.
temp = temp.next → node(15).
temp.data == 15 → the loop ends: found it.
temp is not null.
temp.prev (10) is not null → we are not removing the head.
temp.prev.next = temp.next: forward link 10 → 25; 15 is skipped.
temp.next (25) is not null → we are not removing the tail.
temp.next.prev = temp.prev: backward link 25 → 10. 1 ⇄ 10 ⇄ 25. Search O(n), relinking O(1).
Node temp = head; while (temp != null && temp.data != data) temp = temp.next; if (temp == null) return; // not found if (temp.prev != null) temp.prev.next = temp.next; else head = temp.next; // removing the head if (temp.next != null) temp.next.prev = temp.prev; else tail = temp.prev; // removing the tail
Doubly Linked List · Step through the code
Printing a List Backward
temp = tail: the last node is known directly; no walk to the end.
Print the heading.
temp = node(25) is not null.
Print 25.
temp = temp.prev → node(15).
temp = node(15) is not null.
Print 15.
temp = temp.prev → node(10).
temp = node(10) is not null.
Print 10.
temp = temp.prev → node(1).
temp = node(1) is not null.
Print 1.
temp = temp.prev → null (1's prev field).
temp == null → the loop ends.
Print "null". Forward printing is the same: start at head and follow next. Both are O(n).
void printBackward() { Node temp = tail; System.out.print("Backward: "); while (temp != null) { System.out.print(temp.data + " <-> "); temp = temp.prev; } System.out.println("null"); }
Doubly Linked List
Sentinel Nodes: Header and Trailer
null checks, no head/tail updates.header.next and stops at trailer.Doubly Linked List · Step through the code
Code Trace: Inserting and Deleting with Sentinels
Empty list: just the two sentinels, pointing to each other. size = 0. Only the sentinels' outer ends are null.
addFirst(10): addBetween(10, header, header.next). In an empty list, header.next is the trailer.
new Node(10): a new node with both links null.
newNode.prev = pred → node(—).
newNode.next = succ → node(—). The new node is ready; the list doesn't see it yet.
pred.next = newNode: forward — → 10.
succ.prev = newNode: now linked backward too; size = 1. No if: pred and succ always exist.
addFirst(5): addBetween(5, header, header.next) — 5 goes between the header and 10. Same code, no special case.
new Node(5): a new node with both links null.
newNode.prev = pred → node(—).
newNode.next = succ → node(10). The new node is ready; the list doesn't see it yet.
pred.next = newNode: forward — → 5.
succ.prev = newNode: now linked backward too; size = 2. No if: pred and succ always exist.
remove(d), d = node(10) (the last real node). Thanks to the sentinels, both neighbors are guaranteed to exist.
d.prev.next = d.next: 5 now points straight to the trailer.
d.next.prev = d.prev: 10 is skipped in both directions; size = 1. Even when the last node goes, there is no tail update → every operation is O(1).
void addBetween(int v, Node pred, Node succ) { Node newNode = new Node(v); newNode.prev = pred; newNode.next = succ; pred.next = newNode; succ.prev = newNode; size++; } void addFirst(int v) { addBetween(v, header, header.next); } void remove(Node d) { d.prev.next = d.next; d.next.prev = d.prev; size--; }
Doubly Linked List
Multi-Way Links: Turning a Matrix into a Linked Structure
Each node holds two links: class Node { int data; Node right, down; } (constructor: Node(int data))
void display(Node start) { Node down = start; while (down != null) { // rows Node right = down; while (right != null) { // columns System.out.print(right.data + " "); right = right.right; } System.out.println(); down = down.down; } }
Output, row by row: 1 2 3 / 4 5 6 / 7 8 9. Each node is visited once: O(rows · columns).
Doubly Linked List
Building the Linked Structure from a Matrix
Node build(int[][] m) { int r = m.length, c = m[0].length; Node[][] d = new Node[r][c]; for (int i = r - 1; i >= 0; i--) for (int j = c - 1; j >= 0; j--) { Node n = new Node(m[i][j]); if (j + 1 < c) n.right = d[i][j+1]; if (i + 1 < r) n.down = d[i+1][j]; d[i][j] = n; } return d[0][0]; }
d table? A recursive version that calls build(i, j+1) and build(i+1, j) directly rebuilds the same cell over and over (an exponential number of nodes; the right and down paths don't share a common node).Doubly Linked List · Step through the code
Code Trace: build(m) — a 2×3 matrix
d: a 2×3 array of node references, all null. Nodes will be created starting from the bottom right.
(i=1, j=2): new Node(6); no right (last column), no down (last row). Neighbors already exist; no cell is built twice.
(i=1, j=1): new Node(5); right → 6, no down (last row). Neighbors already exist; no cell is built twice.
(i=1, j=0): new Node(4); right → 5, no down (last row). Neighbors already exist; no cell is built twice.
(i=0, j=2): new Node(3); no right (last column), down → 6. Neighbors already exist; no cell is built twice.
(i=0, j=1): new Node(2); right → 3, down → 5. Neighbors already exist; no cell is built twice.
(i=0, j=0): new Node(1); right → 2, down → 4. Neighbors already exist; no cell is built twice.
Return d[0][0] (1): the whole structure is reachable from the top-left corner through right/down. 6 cells, 6 nodes → O(r·c).
Node build(int[][] m) { int r = m.length, c = m[0].length; Node[][] d = new Node[r][c]; for (int i = r - 1; i >= 0; i--) for (int j = c - 1; j >= 0; j--) { Node n = new Node(m[i][j]); if (j + 1 < c) n.right = d[i][j+1]; if (i + 1 < r) n.down = d[i+1][j]; d[i][j] = n; } return d[0][0]; }
Circularly Linked List
Circularly Linked List
- The last node points to the first node instead of
null, so the list forms a cycle (a ring). - Each node still points to the node after it; the list has no
nulllinks. - Keeping
tailalone is enough: the head istail.next. - Uses: jobs that take turns (round-robin scheduling), turn order in multiplayer games, a looping playlist.
Circularly Linked List
The Circular List Class
public class CircularLinkedList { class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } private Node tail; // head = tail.next private int size; }
tail.next, so both ends are reachable in O(1).tail == null. One node: tail.next == tail.Circularly Linked List · Step through the code
Printing a Circular List
The list is not empty. Only tail is kept; the last node points to the head (the bottom link).
The head is tail.next: current = 1.
current (1) != tail (16) → loop.
Print 1.
current = current.next → node(8).
current (8) != tail (16) → loop.
Print 8.
current = current.next → node(10).
current (10) != tail (16) → loop.
Print 10.
current = current.next → node(16).
current == tail → the loop ends (we never reach null; the condition is != tail).
The last node is printed separately after the loop. Each node once: O(n).
void print() { if (tail == null) return; Node current = tail.next; while (current != tail) { System.out.print(current.data + " "); current = current.next; } System.out.print(current.data + " "); }
Circularly Linked List
Detecting a Cycle in General: Floyd's Algorithm
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; }
- Each round, the slow pointer moves one node and the fast pointer two.
- If there is a cycle, the two pointers eventually meet inside it.
- If there is no cycle, the fast pointer reaches
null. - The cycle need not lead back to the
headnode.
head is not enough: the cycle may loop back to a node in the middle of the list.Circularly Linked List · Step through the code
Code Trace: hasCycle (Floyd)
The list is 1 → … → 6, and 6 points back to 3 (the cycle does not return to the head). Both pointers start at the head.
Round 1: fast (1) and fast.next (2) are not null.
slow moves 1 step → node(2).
fast moves 2 steps → node(3).
slow (2) ≠ fast (3) → continue.
Round 2: fast (3) and fast.next (4) are not null.
slow moves 1 step → node(3).
fast moves 2 steps → node(5).
slow (3) ≠ fast (5) → continue.
Round 3: fast (5) and fast.next (6) are not null.
slow moves 1 step → node(4).
fast moves 2 steps → node(3).
slow (4) ≠ fast (3) → continue. fast has entered the cycle and is closing in on slow from behind.
Round 4: fast (3) and fast.next (4) are not null.
slow moves 1 step → node(5).
fast moves 2 steps → node(5).
slow == fast (node 5) → return true. Inside the cycle, fast gains one node on slow 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; }
Circularly Linked List · Step through the code
Inserting at the Tail of a Circular List — O(1)
addLast(1): create the new node.
tail == null → the list is empty.
tail = temp.
tail.next = tail: the single node points to itself; the ring is closed at once.
size++.
addLast(8): create the new node.
The list is not empty → else.
temp.next = tail.next: the new node points to the head (1).
tail.next = temp: the old tail (1) points to the new node.
tail = temp: tail is now 8.
size++.
addLast(10): create the new node.
The list is not empty → else.
temp.next = tail.next: the new node points to the head (1).
tail.next = temp: the old tail (8) points to the new node.
tail = temp: tail is now 10.
size++. Result: 1 → 8 → 10 → (1). No walk: O(1).
Node temp = new Node(value); if (tail == null) { tail = temp; tail.next = tail; } else { temp.next = tail.next; tail.next = temp; tail = temp; } size++;
Circularly Linked List
Inserting and Deleting at the Head of a Circular List
void addFirst(int value) { Node temp = new Node(value); if (tail == null) { tail = temp; tail.next = tail; } else { temp.next = tail.next; tail.next = temp; } // tail unchanged size++; }
void removeFirst() { if (tail == null) return; Node head = tail.next; if (head == tail) // single node tail = null; else tail.next = head.next; size--; }
tail = temp: the new node enters the ring at the same spot; only which node counts as the "tail" changes.Circularly Linked List · Step through the code
Code Trace: Circular addFirst(5)
addFirst(5): a new node. Ring: 1 → 8 → 10 → (1), tail = 10.
The list is not empty → else.
temp.next = tail.next: 5 points to the old head (1).
tail.next = temp: 10 now points to 5 → 5 is the new head. tail doesn't change.
size++. Ring: 5 → 1 → 8 → 10 → (5). O(1); the only difference from inserting at the tail is the missing tail = temp.
void addFirst(int value) { Node temp = new Node(value); if (tail == null) { tail = temp; tail.next = tail; } else { temp.next = tail.next; tail.next = temp; } // tail unchanged size++; }
Circularly Linked List · Step through the code
Code Trace: Circular removeFirst()
Ring: 1 → 8 → 10 → (1), tail = 10. Not empty.
head = tail.next: the head node to delete (1).
head != tail → more than one node.
tail.next = head.next: 10 now points to 8; 1 has left the ring.
size--. Ring: 8 → 10 → (8). O(1).
void removeFirst() { if (tail == null) return; Node head = tail.next; if (head == tail) // single node tail = null; else tail.next = head.next; size--; }
Circularly Linked List
Deleting at the Tail of a Circular List — O(n)
void removeLast() { if (tail == null) return; if (tail.next == tail) tail = null; // single node else { Node temp = tail.next; while (temp.next != tail) // second to last temp = temp.next; temp.next = tail.next; // link to the head tail = temp; } size--; }
Finding the second-to-last node means walking around the ring: O(n). In a doubly linked circular list, tail.prev makes it O(1).
Circularly Linked List · Step through the code
Code Trace: Circular removeLast()
removeLast(): ring 1 → 8 → 10 → 16 → (1), tail = 16. Not empty.
tail.next != tail → not a single node.
temp = tail.next: start at the head (1).
node(1).next = 8 ≠ tail → advance.
temp = temp.next → node(8).
node(8).next = 10 ≠ tail → advance.
temp = temp.next → node(10).
node(10).next == tail → temp is at the second-to-last node.
temp.next = tail.next: 10 points to the head (1); 16 has left the ring.
tail = temp: tail is now 10.
size--. Ring: 1 → 8 → 10 → (1). We walked to find the previous node: O(n).
if (tail == null) return; if (tail.next == tail) tail = null; // single node else { Node temp = tail.next; while (temp.next != tail) // second to last temp = temp.next; temp.next = tail.next; // link to the head tail = temp; } size--;
Circularly Linked List · Step through the code
Code Trace: Round-Robin with rotate()
Ring 1 → 8 → 10 → (1), tail = 10, head = tail.next = 1. Three jobs take turns on the processor.
Round 1: the job at the head, 1, is served (printed).
rotate(): tail = tail.next → tail = 1. No link changes, one pointer moves: O(1). New head: 8.
Round 2: the job at the head, 8, is served (printed).
rotate(): tail = tail.next → tail = 8. No link changes, one pointer moves: O(1). New head: 10.
Round 3: the job at the head, 10, is served (printed).
rotate(): tail = tail.next → tail = 10. No link changes, one pointer moves: O(1). New head: 1.
Round 4: the job at the head, 1, is served (printed).
rotate(): tail = tail.next → tail = 1. No link changes, one pointer moves: O(1). Output 1 8 10 1: the jobs take fair turns.
void rotate() { // Goodrich: rotate() if (tail != null) tail = tail.next; // old head becomes the tail } // round-robin: serve the head each round for (int round = 1; round <= 4; round++) { System.out.print(tail.next.data + " "); list.rotate(); }
Summary
Array or Linked List?
| Criterion | Array | Linked list |
|---|---|---|
| Access the i-th item | O(1): compute the address | O(n): walk from the head |
| Insert / delete at the front | O(n): shifting | O(1) |
| Insert after a known position | O(n) | O(1): two links |
| Size | fixed; growing costs an O(n) copy | dynamic; one new per insertion |
| Overhead / cache | unused capacity; cache-friendly | a reference per node; scattered access |
Frequent random access and a fixed size → array. Frequent insertion/deletion at the ends and an unpredictable size → linked list (stack, queue).
Summary
Common Mistakes with Linked Lists
head.data while head is null → NullPointerException.if (head == null) return;head changes first, the old list is lost.newNode.next = head; head = newNode;head during a traversalAfter printing, the list is unreachable.Node temp = head;tailAfter the only node is deleted, tail still points to it.if (head == null) tail = null;prev isn't updated, backward traversal breaks.next.prev = newNode;!= null in a circular listA ring has no null → infinite loop.while (p != tail) …Summary
Operation Costs Across Linked Lists
| Operation | Singly (head only) | Singly (head + tail) | Doubly (head + tail) | Circular (tail only) |
|---|---|---|---|---|
| Insert at head | O(1) | O(1) | O(1) | O(1) |
| Insert at tail | O(n) | O(1) | O(1) | O(1) |
| Delete at head | O(1) | O(1) | O(1) | O(1) |
| Delete at tail | O(n) | O(n) | O(1) | O(n) |
| Search / i-th item | O(n) | O(n) | O(n) | O(n) |
| Delete a known node | O(n)* | O(n)* | O(1) | O(n)* |
* Finding the previous node takes a walk. Inserting after a known node is O(1) in every kind. In an array, by contrast, reaching the i-th item is O(1) and inserting at the front O(n).
Summary
Try It: Singly Linked List
Summary
Sample Problems
- What does it take to make inserting at the tail of a singly linked list O(1)? Which operation is still O(n)?
- What happens if the two lines of
addFirstare swapped (head = newNode;first)? - How do you find the middle of a list in one pass, without computing its length?
- How can you tell whether a singly linked list has a cycle (the last node linked back to an earlier one)?
- What does it cost to delete the
tailnode of a doubly linked list? Why is it different for a singly linked list? - Why does a circular list keep
tailrather thanhead?
Show answers
- A
tailpointer. Deleting at the tail stays O(n) (we cannot step back to the previous node). - The new node points to itself (
newNode.next = newNode) and the old list is lost. - Slow (1 step) and fast (2 steps) pointers: when fast reaches the end, slow is in the middle.
- The same two pointers (Floyd): if fast reaches null there is no cycle; if it catches up with slow, there is one.
- O(1):
tail = tail.prev. In a singly linked list, reaching the previous node means walking from the head: O(n). - Head =
tail.next; one pointer gives O(1) access to both ends.
Summary
Exercises
- In the list 3 → 5 → 7, what is the list after
head.next = head.next.next;? What happens to 5? - What does
int mystery(Node d) { return d == null ? 0 : d.data + mystery(d.next); }return for 2 → 4 → 6? - How do you find the k-th item from the end of a singly linked list in one pass, without knowing its length?
- In a doubly linked list with sentinels, how many link assignments does inserting into an empty list take? Why is no
ifneeded? - Circular list 1 → 8 → 10 (tail = 10). After two calls to
rotate(), which item is at the head? - How many comparisons and swaps does
sort()make on the list 3 → 1 → 2?
Answers / hints
- 3 → 7; if no reference to 5 remains, the garbage collector reclaims it.
- 12: a recursive sum; O(n) time, O(n) call stack.
- Two pointers:
fastgoes k steps ahead, then both move together; whenfastis null,slowis the answer. - 4 (newNode.prev, newNode.next, pred.next, succ.prev); the sentinel neighbors always exist.
- 10 (tail moves to 1, then to 8; head = tail.next).
- 3 comparisons, 2 swaps → 1 → 2 → 3.
Summary
Further Reading
- Goodrich, Tamassia, and Goldwasser, Data Structures and Algorithms in Java, 6th ed., 2014.
- Lafore, Data Structures and Algorithms in Java, 2nd ed., 2002.
- Sedgewick and Wayne, Algorithms, 4th ed., 2011.