Chapter 5: Linked Lists

Data Structures
Nodes and linksSingly linked listInsert · delete · traverse ReversalDoubly linked listCircular listSentinel nodes
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Node structure

Explain nodes, links, and references.

Core operations

Implement insertion, deletion, search, and traversal.

Kinds of lists

Compare singly, doubly, and circularly linked lists.

Cost analysis

Evaluate the time and space costs of linked-list operations.

Basics

Kinds of Linked Lists

Singly linkedEach node points only to the next one; the last node points to null.
1081null
Doubly linkedEach node points to both the previous and the next node, so we can walk either way.
1081nullnull
Circularly linkedThe last node points back to the first instead of null, closing the list into a ring.
1081

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 (head in 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; null in the last node.
10811115nullheaddatanext

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.
103F8address 1A085B0address 2C412C4address 3F811nulladdress 5B0memory (in address order)head = 1A0

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

int data
// Node class
class Node {
    int data;
    Node next;
    Node(int data) {
        this.data = data;
        this.next = null;
    }
}
Generic version
// 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 next field starts as null and changes once the node is linked into a list.

Basics · Step through the code

Building a Singly Linked List

10nullfirst

new Node(10): creates a node with data = 10 and next = null; first points to it.

101nullfirstsecond

The second node (1) is created. The nodes are not linked yet.

1018nullfirstsecondthird

The third node (8) is created. Each node can sit anywhere in memory.

101811nullfirstsecondthirdfourth

The fourth node (11) is created. We have four separate nodes, each with a next field of null (⁄).

101811nullfirstsecondthirdfourth

first.next = second: the next field of 10 now points to 1 (orange).

101811nullfirstsecondthirdfourth

second.next = third: links 1 → 8.

101811nullfirstsecondthirdfourth

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

OperationHow it worksCost
Insert at headNew node points to the old head; head becomes the new nodeO(1)
Insert at tailWalk to the last node (no walk with a tail pointer)O(n) · O(1)
Delete at headMove head to the next nodeO(1)
Delete at tailMust find the second-to-last nodeO(n)
Search · print · lengthWalk from head to tailO(n)
Reverse · mergeOne 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

list objectsize = 3tailhead1081null
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–TamassiaIn these slidesPurposeCost
size(), isEmpty()size(), isEmpty()the size field is updated by every operationO(1)
first(), last()first(), isEmpty() ? null : tail.datareturn null on an empty listO(1)
addFirst, addLastaddFirst, addLastboth constant time with a tail pointer; inserting into an empty list also sets tailO(1)
removeFirst()removeFirst()returns the removed nodeO(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.
Inserting or deleting in the middle is O(1) only if we already know the position (the previous node); finding it still takes an O(n) walk.

Singly Linked: Traversal and Insertion · Step through the code

Traversing and Printing a List

101811nullheadtemp

temp = head: the walk starts at the head. head never changes; only temp moves.

101811nullheadtemp

Print the heading.

101811nullheadtemp

temp != null (node 10) → enter the loop body.

101811nullheadtemp

Print temp.data = 10.

101811nullheadtemp

temp = temp.next → temp is now node(1).

101811nullheadtemp

temp = node(1) ≠ null → continue.

101811nullheadtemp

Print temp.data = 1.

101811nullheadtemp

temp = temp.next → temp is now node(8).

101811nullheadtemp

temp = node(8) ≠ null → continue.

101811nullheadtemp

Print temp.data = 8.

101811nullheadtemp

temp = temp.next → temp is now node(11).

101811nullheadtemp

temp = node(11) ≠ null → continue.

101811nullheadtemp

Print temp.data = 11.

101811nullheadtemp

temp = temp.next → temp is now null (the last node's next field).

101811nullheadtemp

temp == null → the condition is false and the loop ends.

101811nullheadtemp

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

O(n)
int listLength() {
    int length = 0;
    Node temp = head;
    while (temp != null) {
        length++;
        temp = temp.next;
    }
    return length;
}
O(n)
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
}
The traversal pattern: start with 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)

101811nullheadtemp

search(8): start at the head with temp = head.

101811nullheadtemp

position = 0: counts temp's place (index) in the list.

101811nullheadtemp

temp = node(10) ≠ null → loop.

101811nullheadtemp

10 == 8? No → continue.

101811nullheadtemp

position++ → 1.

101811nullheadtemp

temp = temp.next → node(1).

101811nullheadtemp

temp = node(1) ≠ null → loop.

101811nullheadtemp

1 == 8? No → continue.

101811nullheadtemp

position++ → 2.

101811nullheadtemp

temp = temp.next → node(8).

101811nullheadtemp

temp = node(8) ≠ null → loop.

101811nullheadtemp

8 == 8 → found the target.

101811nullheadtemp

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)

nullhead

Call addFirst(11). The list is empty: head = null.

11nullnullheadnewNode

Create node 11; its next is null.

11nullnullheadnewNode

newNode.next = head: head is null, so 11's next stays null.

11nullheadnewNode

head = newNode: head moves to 11: 11 → null.

11nullhead, tailnewNode

if (tail == null) tail = head: the list was empty, so 11 is both head and tail. size++ → 1.

11nullhead, tail

Call addFirst(8). List: 11 → null.

118nullhead, tailnewNode

Create node 8; its next is null.

118nullhead, tailnewNode

newNode.next = head: 8 points to the old head (11). Changing head first would lose 11.

118nullheadnewNodetail

head = newNode: head moves to 8: 8 → 11 → null.

118nullheadnewNodetail

tail is not null, so it stays at 11. size++ → 2.

118nullheadtail

Call addFirst(1). List: 8 → 11 → null.

1181nullheadnewNodetail

Create node 1; its next is null.

1181nullheadnewNodetail

newNode.next = head: 1 points to the old head (8). Changing head first would lose 8.

1181nullheadnewNodetail

head = newNode: head moves to 1: 1 → 8 → 11 → null.

1181nullheadnewNodetail

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)

10nullnullheadnewNode

addLast(10): create the new node.

10nullnullheadnewNode

head == null → the list is empty.

10nullheadnewNode

head = newNode: a one-node list.

10nullheadnewNode

return: no walk needed.

101nullheadnewNode

addLast(1): create the new node.

101nullheadnewNode

The list is not empty → walk to the end.

101nullheadnewNodetemp

temp = head: start at the head to find the last node.

101nullheadnewNodetemp

node(10).next == null → temp is at the last node; the loop ends.

101nullheadnewNodetemp

temp.next = newNode: 10 → 1 → null.

1018nullheadnewNode

addLast(8): create the new node.

1018nullheadnewNode

The list is not empty → walk to the end.

1018nullheadnewNodetemp

temp = head: start at the head to find the last node.

1018nullheadnewNodetemp

node(10).next is not null → advance.

1018nullheadnewNodetemp

temp = temp.next → node(1).

1018nullheadnewNodetemp

node(1).next == null → temp is at the last node; the loop ends.

1018nullheadnewNodetemp

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)

11815nullheadtailold tail
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++;
    }
}
No walk: O(1)The last node is known; two assignments suffice.
The priceEvery operation must keep tail up to date (inserting into an empty list, deleting the last node).
Deleting at the tail is still O(n)In a singly linked list we cannot step back from tail.

Singly Linked: Traversal and Insertion · Step through the code

Code Trace: addLast with tail

10nullnullhead, tailnewNode

addLast(10): create the new node.

10nullnullhead, tailnewNode

head == null → the list is empty.

10nullhead, tailnewNode

head = tail = newNode: the single node is both head and tail.

10nullhead, tailnewNode

size++ → 1.

101nullhead, tailnewNode

addLast(1): create the new node.

101nullhead, tailnewNode

The list is not empty; the last node is already known: node(10).

101nullhead, tailnewNode

tail.next = newNode: links 10 → 1. No walk.

101nullheadtailnewNode

tail = newNode: tail is now 1.

101nullheadtailnewNode

size++ → 2.

1018nullheadtailnewNode

addLast(8): create the new node.

1018nullheadtailnewNode

The list is not empty; the last node is already known: node(1).

1018nullheadtailnewNode

tail.next = newNode: links 1 → 8. No walk.

1018nullheadtailnewNode

tail = newNode: tail is now 8.

1018nullheadtailnewNode

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++;
}
Index 0Same as inserting at the head; handled separately.
Order mattersFirst (1), then (2); the reverse cuts off the rest of the list.
CostWalking to the position is O(index), O(n) in the worst case; linking is O(1).

Singly Linked: Traversal and Insertion · Step through the code

Code Trace: addAt(5, 2)

101811nullheadtemp

addAt(5, 2): index ≠ 0, so this is not an insert at the head. temp = head; we advance index − 1 = 1 step.

101811nullheadtemp

i = 0: 0 < 1 and temp != null → loop body.

101811nullheadtemp

temp = temp.next → node(1).

101811nullheadtemp

i = 1: 1 < 1 is false → the loop ends. temp is at the node with index 1 (just before the insertion point).

101811nullheadtemp

temp is not null → the position is valid; no error message.

1018115nullheadtempnewNode

Create the new node (5). (The drawing shifts 8 and 11 to the right; nothing moves in memory.) 1 still points to 8.

1018115nullheadtempnewNode

(1) newNode.next = temp.next: 5 points to 8. The list has not changed yet.

1018115nullheadtempnewNode

(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)

10111nullhead

Call 1: head is not null (10 → 1 → 11 → null).

10111nullheadtemp

temp = head: save the node being removed (10).

10111nullheadtemp

head = head.next: head is node(1); 10 is now unreachable.

10111nullheadtemp

temp.next = null: 10 is fully detached.

10111nullheadtemp

return temp: 10 goes back to the caller. Once unreferenced, it is reclaimed by the GC. O(1).

111nullhead

Call 2: head is not null (1 → 11 → null).

111nullheadtemp

temp = head: save the node being removed (1).

111nullheadtemp

head = head.next: head is node(11); 1 is now unreachable.

111nullheadtemp

temp.next = null: 1 is fully detached.

111nullheadtemp

return temp: 1 goes back to the caller. Once unreferenced, it is reclaimed by the GC. O(1).

11nullhead

Call 3: head is not null (11 → null).

11nullheadtemp

temp = head: save the node being removed (11).

11nullnullheadtemp

head = head.next: head is null and the list is empty; 11 is now unreachable.

11nullnullheadtemp

temp.next = null: 11 is fully detached.

11nullnullheadtemp

return temp: 11 goes back to the caller. Once unreferenced, it is reclaimed by the GC. O(1).

nullhead

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)

101811nullhead

The list is not empty.

101811nullhead

head.next is not null → there is more than one node.

101811nullheadtemp

temp = head. Goal: find the second-to-last node (its link will change).

101811nullheadtemp

node(10).next.next = 8 ≠ null → advance.

101811nullheadtemp

temp = temp.next → node(1).

101811nullheadtemp

node(1).next.next = 11 ≠ null → advance.

101811nullheadtemp

temp = temp.next → node(8).

101811nullheadtemp

node(8).next.next == null → temp is at the second-to-last node.

101811nullheadtemp

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.");
}
1018nullprevtemp

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)

101811nullheadprev

remove(8): the list is not empty and the head 10 ≠ 8 (both ifs passed). prev = head.

101811nullheadprevtemp

temp = head.next: the two pointers walk side by side; deleting needs the previous node.

101811nullheadprevtemp

temp = node(1) is not null → loop.

101811nullheadprevtemp

1 == 8? No.

101811nullheadprev, temp

prev = temp → node(1).

101811nullheadprevtemp

temp = temp.next → node(8).

101811nullheadprevtemp

temp = node(8) is not null → loop.

101811nullheadprevtemp

8 == 8 → found the node to delete.

101811nullheadprevtemp

prev.next = temp.next: 1 now points to 11; 8 is "skipped".

101811nullheadprevtemp

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;
}
Three pointersprev, current, next
No new nodesEach round reverses one link.
O(n) timeO(1) extra space
Input:108111nullOutput:111810null

Singly Linked: Deletion and Other Operations · Step through the code

Code Trace: reverse()

108111nullhead, currentnullprevnullnext

Start: prev = null, current = head (10), next = null. No new nodes will be created.

108111nullhead, currentnullprevnullnext

Round 1: current = node(10) is not null.

108111nullhead, currentnullprevnext

1) next = current.next = node(8): so the rest of the list survives the cut.

108111nullhead, currentnullprevnext

2) current.next = prev: 10 now points to null (link reversed).

108111nullhead, prevcurrent, next

3–4) prev = current; current = next: both pointers move one node forward.

108111nullhead, prevcurrent, next

Round 2: current = node(8) is not null.

108111nullhead, prevcurrentnext

1) next = current.next = node(1): so the rest of the list survives the cut.

108111nullhead, prevcurrentnext

2) current.next = prev: 8 now points to node(10) (link reversed).

108111nullheadprevcurrent, next

3–4) prev = current; current = next: both pointers move one node forward.

108111nullheadprevcurrent, next

Round 3: current = node(1) is not null.

108111nullheadprevcurrentnext

1) next = current.next = node(11): so the rest of the list survives the cut.

108111nullheadprevcurrentnext

2) current.next = prev: 1 now points to node(8) (link reversed).

108111nullheadprevcurrent, next

3–4) prev = current; current = next: both pointers move one node forward.

108111nullheadprevcurrent, next

Round 4: current = node(11) is not null.

108111nullheadprevcurrentnullnext

1) next = current.next = null: so the rest of the list survives the cut.

108111headprevcurrentnullnext

2) current.next = prev: 11 now points to node(1) (link reversed).

108111headprevnullcurrent, next

3–4) prev = current; current = next: both pointers move one node forward.

108111headprevnullcurrent, next

current == null → the loop ends; prev is at the old last node (11).

108111head, prevnullcurrent, next

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

1081115nullhead

The list is not empty (an empty list throws an exception).

1081115nullhead, slowfast

Both pointers start at the head. We find the middle without knowing the length.

1081115nullhead, slowfast

fast = node(10) and fast.next = node(8) are not null → round 1.

1081115nullheadslowfast

slow moves 1 step → node(8).

1081115nullheadslowfast

fast moves 2 steps → node(1).

1081115nullheadslowfast

fast = node(1) and fast.next = node(11) are not null → round 2.

1081115nullheadslowfast

slow moves 1 step → node(1).

1081115nullheadslowfast

fast moves 2 steps → node(5).

1081115nullheadslowfast

fast.next == null → fast has reached the end; the loop ends. In 2 rounds slow took 2 steps and fast took 4.

1081115nullheadslowfast

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

list:357nullnewList:357nullseparate objects:changing oneleaves the other alone
SinglyLinkedList copy() {
    SinglyLinkedList newList =
        new SinglyLinkedList();
    Node temp = head;
    while (temp != null) {
        newList.addLast(temp.data);
        temp = temp.next;
    }
    return newList;
}
Deep copyNew nodes are created; writing newList.head = head would only give a second reference to the same list.
CostIf 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()

listnewList1018nullhead

Create a new, empty list. Writing newList.head = head would not be a copy, just a second reference to the same nodes.

listnewList1018nullhead, temp

temp = head: walk the original list from the head.

listnewList1018nullhead, temp

temp = node(10) is not null.

listnewList101810nullnullhead, temp

newList.addLast(10): a new node goes on the end of the copy.

listnewList101810nullnullheadtemp

temp = temp.next → node(1).

listnewList101810nullnullheadtemp

temp = node(1) is not null.

listnewList1018101nullnullheadtemp

newList.addLast(1): a new node goes on the end of the copy.

listnewList1018101nullnullheadtemp

temp = temp.next → node(8).

listnewList1018101nullnullheadtemp

temp = node(8) is not null.

listnewList10181018nullnullheadtemp

newList.addLast(8): a new node goes on the end of the copy.

listnewList10181018nullnullheadtemp

temp = temp.next → null.

listnewList10181018nullnullheadtemp

temp == null → the loop ends.

listnewList10181018nullnullheadtemp

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;
    }
}
IdeaKeep the values seen so far in a second list; skip any node that repeats one.
CostA search in the seen list for every node: O(n²). With a hash set, O(n).
NoteThe first node is never a duplicate, so no deletion happens while 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)

35375nullheadnullprevtemp

Start (earlier lines): seen is empty, prev = null, temp = head. temp = node(3) is not null.

35375nullheadnullprevtemp

v = 3.

35375nullheadnullprevtemp

seen.contains(3) → false: 3 is new.

35375nullheadprev, temp

seen.addFirst(3); prev = temp: the node stays; prev moves to it.

35375nullheadprevtemp

temp = temp.next → node(5).

35375nullheadprevtemp

temp = node(5) is not null.

35375nullheadprevtemp

v = 5.

35375nullheadprevtemp

seen.contains(5) → false: 5 is new.

35375nullheadprev, temp

seen.addFirst(5); prev = temp: the node stays; prev moves to it.

35375nullheadprevtemp

temp = temp.next → node(3).

35375nullheadprevtemp

temp = node(3) is not null.

35375nullheadprevtemp

v = 3.

35375nullheadprevtemp

seen.contains(3) → true: 3 was seen before; this node is a duplicate.

35375nullheadprevtemp

prev.next = temp.next: 5 → node(7); the duplicate 3 is skipped. prev stays put.

35375nullheadprevtemp

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)

35375nullheadprevtemp

temp = node(7) is not null.

35375nullheadprevtemp

v = 7.

35375nullheadprevtemp

seen.contains(7) → false: 7 is new.

35375nullheadprev, temp

seen.addFirst(7); prev = temp: the node stays; prev moves to it.

35375nullheadprevtemp

temp = temp.next → node(5).

35375nullheadprevtemp

temp = node(5) is not null.

35375nullheadprevtemp

v = 5.

35375nullheadprevtemp

seen.contains(5) → true: 5 was seen before; this node is a duplicate.

35375nullheadprevtemp

prev.next = temp.next: 7 → null; the duplicate 5 is skipped. prev stays put.

35375nullheadprevtemp

temp = temp.next → null.

35375nullheadprevtemp

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 → 4 → 7 and 2 → 3 → 8
⇒ 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)

l1l2result147238nullnullp1p2

result is a new, empty list. p1 and p2 start at the heads of the two sorted lists.

l1l2result147238nullnullp1p2

Neither list is exhausted → compare.

l1l2result147238nullnullp1p2

1 ≤ 2 → true: l1 has the smaller value.

l1l2result1472381nullnullnullp1p2

Append 1; p1 advances.

l1l2result1472381nullnullnullp1p2

Neither list is exhausted → compare.

l1l2result1472381nullnullnullp1p2

4 ≤ 2 → false: l2 has the smaller value.

l1l2result14723812nullnullnullp1p2

Append 2; p2 advances.

l1l2result14723812nullnullnullp1p2

Neither list is exhausted → compare.

l1l2result14723812nullnullnullp1p2

4 ≤ 3 → false: l2 has the smaller value.

l1l2result147238123nullnullnullp1p2

Append 3; p2 advances.

l1l2result147238123nullnullnullp1p2

Neither list is exhausted → compare.

l1l2result147238123nullnullnullp1p2

4 ≤ 8 → true: l1 has the smaller value.

l1l2result1472381234nullnullnullp1p2

Append 4; p1 advances.

l1l2result1472381234nullnullnullp1p2

Neither list is exhausted → compare.

l1l2result1472381234nullnullnullp1p2

7 ≤ 8 → true: l1 has the smaller value.

l1l2result14723812347nullnullnullnullp1p2

Append 7; p1 advances.

l1l2result14723812347nullnullnullnullp1p2

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)

l1l2result14723812347nullnullnullnullp1p2

Leftovers: p1 == null → the first loop never runs.

l1l2result14723812347nullnullnullnullp1p2

p2 = node(8) is not null.

l1l2result147238123478nullnullnullnullp1, p2

Append 8; p2 advances.

l1l2result147238123478nullnullnullnullp1, p2

p2 == null → done.

l1l2result147238123478nullnullnullnullp1, p2

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;
    }
}
Swap valuesThe nodes stay in place; only their data fields change.
O(n²)Each node is compared with every node after it: n(n−1)/2.
BetterMerge sort runs in O(n log n) on a linked list and needs no extra array.

Singly Linked: Deletion and Other Operations · Step through the code

Code Trace: sort() (4 → 1 → 3 → 2)

4132nullhead, current

List 4 → 1 → 3 → 2. current starts at the head; the nodes stay in place and only the data fields change.

4132nullhead, currentother

other = current.next → node(1). current (4) is compared with each later node.

1432nullhead, currentother

4 > 1 → swap the values (temp = 4). List: 1 → 4 → 3 → 2.

1432nullhead, currentother

1 > 3? No → no swap; other advances.

1432nullhead, currentother

1 > 2? No → no swap; other advances.

1432nullheadcurrent

The inner loop is done: the smallest remaining value is now in current's node. current advances → node(4).

1432nullheadcurrentother

other = current.next → node(3). current (4) is compared with each later node.

1342nullheadcurrentother

4 > 3 → swap the values (temp = 4). List: 1 → 3 → 4 → 2.

1243nullheadcurrentother

3 > 2 → swap the values (temp = 3). List: 1 → 2 → 4 → 3.

1243nullheadcurrent

The inner loop is done: the smallest remaining value is now in current's node. current advances → node(4).

1243nullheadcurrentother

other = current.next → node(3). current (4) is compared with each later node.

1234nullheadcurrentother

4 > 3 → swap the values (temp = 4). List: 1 → 2 → 3 → 4.

1234nullheadcurrent

The inner loop is done: the smallest remaining value is now in current's node. current advances → node(4).

1234nullheadcurrentother

other = current.next = null: there is nothing left to compare the last node with.

1234nullheadcurrent

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.
prevdatanextprevious nodenext nodeNode
GainBackward traversal; deleting a known node or the last node in O(1).
PriceA second reference per node; every insertion and deletion must update both directions.

Doubly Linked List

Doubly Linked List: Node and Structure

1101525nullnullheadtail
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)

1015251nullnullheadtailnewNode

addFirst(1): the new node's prev and next fields are null (⁄).

1015251nullnullheadtailnewNode

head is not null → else branch.

1015251nullnullheadtailnewNode

newNode.next = head: forward link 1 → 10.

1015251nullnullheadtailnewNode

head.prev = newNode: backward link 10 → 1 (10's null is gone).

1015251nullnullhead, newNodetail

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)

110152530nullnullheadtailnewNode

addLast(30): create the new node.

110152530nullnullheadtailnewNode

The list is not empty → else. tail gives the last node directly.

110152530nullnullheadtailnewNode

newNode.prev = tail: backward link 30 → 25.

110152530nullnullheadtailnewNode

tail.next = newNode: forward link 25 → 30.

110152530nullnullheadtailnewNode

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)
}
101512(1)(2)(3)(4)temp

Doubly Linked List · Step through the code

Code Trace: addAt(12, 2) — the linking part

110152512nullnullnullnullheadtailtempnewNode

addAt(12, 2): as in the singly linked version, temp has walked to the node at index − 1 = 1 (10). Create the new node.

110152512nullnullnullheadtailtempnewNode

(1) newNode.next = temp.next: 12 → 15. The list has not changed yet.

110152512nullnullheadtailtempnewNode

(2) newNode.prev = temp: backward link 12 → 10.

110152512nullnullheadtailtempnewNode

(3) temp.next.prev = newNode: 15's backward link now points to 12. This must come before (4), while temp.next is still 15.

110152512nullnullheadtailtempnewNode

(4) temp.next = newNode: 10 → 12. Four links changed; swapping (3) and (4) would leave 15 unreachable.

110152512nullnullheadtailtempnewNode

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

O(1)
void removeFirst() {
    if (head == null) return;  // empty
    if (head == tail) {  // single node
        head = tail = null;
    } else {
        head = head.next;
        head.prev = null;
    }
}
O(1)
void removeLast() {
    if (tail == null) return;  // empty
    if (head == tail) {  // single node
        head = tail = null;
    } else {
        tail = tail.prev;
        tail.next = null;
    }
}
To delete at the tail we reach the previous node in one step with 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()

11015nullnullheadtail

List: 1 ⇄ 10 ⇄ 15. Not empty.

11015nullnullheadtail

head != tail → several nodes, else branch.

11015nullnullheadtail

head = head.next: head moves to 10; 1 is now unreachable.

11015nullnullheadtail

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

1101525nullnullheadtail

List: 1 ⇄ 10 ⇄ 15 ⇄ 25; tail points to 25.

1101525nullnullheadtail

head != tail → else branch.

1101525nullnullheadtail

tail = tail.prev: we reach the second-to-last node in one step (a singly linked list would need a walk).

1101525nullnullheadtail

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
}
11015temp

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)

1101525nullnullheadtailtemp

remove(15): temp = head; first we search for the node to delete.

1101525nullnullheadtailtemp

node(1) is not null and 1 ≠ 15 → advance.

1101525nullnullheadtailtemp

temp = temp.next → node(10).

1101525nullnullheadtailtemp

node(10) is not null and 10 ≠ 15 → advance.

1101525nullnullheadtailtemp

temp = temp.next → node(15).

1101525nullnullheadtailtemp

temp.data == 15 → the loop ends: found it.

1101525nullnullheadtailtemp

temp is not null.

1101525nullnullheadtailtemp

temp.prev (10) is not null → we are not removing the head.

1101525nullnullheadtailtemp

temp.prev.next = temp.next: forward link 10 → 25; 15 is skipped.

1101525nullnullheadtailtemp

temp.next (25) is not null → we are not removing the tail.

1101525nullnullheadtailtemp

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

1101525nullnullheadtail, temp

temp = tail: the last node is known directly; no walk to the end.

1101525nullnullheadtail, temp

Print the heading.

1101525nullnullheadtail, temp

temp = node(25) is not null.

1101525nullnullheadtail, temp

Print 25.

1101525nullnullheadtailtemp

temp = temp.prev → node(15).

1101525nullnullheadtailtemp

temp = node(15) is not null.

1101525nullnullheadtailtemp

Print 15.

1101525nullnullheadtailtemp

temp = temp.prev → node(10).

1101525nullnullheadtailtemp

temp = node(10) is not null.

1101525nullnullheadtailtemp

Print 10.

1101525nullnullheadtailtemp

temp = temp.prev → node(1).

1101525nullnullheadtailtemp

temp = node(1) is not null.

1101525nullnullheadtailtemp

Print 1.

1101525nullnullheadtailtemp

temp = temp.prev → null (1's prev field).

1101525nullnullheadtailtemp

temp == null → the loop ends.

1101525nullnullheadtailtemp

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

empty list——headertrailer2 items—510—headertrailer
IdeaPut two fixed nodes that carry no data at the ends of the list (Goodrich–Tamassia: header / trailer).
No special casesEvery real node always has a predecessor and a successor: no null checks, no head/tail updates.
PriceTwo extra nodes; traversal starts at header.next and stops at trailer.

Doubly Linked List · Step through the code

Code Trace: Inserting and Deleting with Sentinels

——nullnullheadertrailer

Empty list: just the two sentinels, pointing to each other. size = 0. Only the sentinels' outer ends are null.

——nullnullheadertrailerpredsucc

addFirst(10): addBetween(10, header, header.next). In an empty list, header.next is the trailer.

——10nullnullnullheadertrailerpredsuccnewNode

new Node(10): a new node with both links null.

——10nullnullheadertrailerpredsuccnewNode

newNode.prev = pred → node(—).

——10nullnullheadertrailerpredsuccnewNode

newNode.next = succ → node(—). The new node is ready; the list doesn't see it yet.

——10nullnullheadertrailerpredsuccnewNode

pred.next = newNode: forward — → 10.

——10nullnullheadertrailerpredsuccnewNode

succ.prev = newNode: now linked backward too; size = 1. No if: pred and succ always exist.

——10nullnullheadertrailerpredsucc

addFirst(5): addBetween(5, header, header.next) — 5 goes between the header and 10. Same code, no special case.

——105nullnullheadertrailerpredsuccnewNode

new Node(5): a new node with both links null.

——105nullnullheadertrailerpredsuccnewNode

newNode.prev = pred → node(—).

——105nullnullheadertrailerpredsuccnewNode

newNode.next = succ → node(10). The new node is ready; the list doesn't see it yet.

——105nullnullheadertrailerpredsuccnewNode

pred.next = newNode: forward — → 5.

——105nullnullheadertrailerpredsuccnewNode

succ.prev = newNode: now linked backward too; size = 2. No if: pred and succ always exist.

——105nullnullheadertrailerd

remove(d), d = node(10) (the last real node). Thanks to the sentinels, both neighbors are guaranteed to exist.

——105nullnullheadertrailerd

d.prev.next = d.next: 5 now points straight to the trailer.

——105nullnullheadertrailerd

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))

123null456null789nullright → down ↓
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];
}
Start at the bottom rightThe right and lower neighbors already exist; each cell gets one node.
O(rows · columns)Each cell is processed once.
Why the 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

m =1 2 34 5 6d[0][0]d[0][1]d[0][2]d[1][0]d[1][1]d[1][2]

d: a 2×3 array of node references, all null. Nodes will be created starting from the bottom right.

m =1 2 34 5 6d[0][0]d[0][1]d[0][2]d[1][0]d[1][1]6right: null

(i=1, j=2): new Node(6); no right (last column), no down (last row). Neighbors already exist; no cell is built twice.

m =1 2 34 5 6d[0][0]d[0][1]d[0][2]d[1][0]56right: null

(i=1, j=1): new Node(5); right → 6, no down (last row). Neighbors already exist; no cell is built twice.

m =1 2 34 5 6d[0][0]d[0][1]d[0][2]456right: null

(i=1, j=0): new Node(4); right → 5, no down (last row). Neighbors already exist; no cell is built twice.

m =1 2 34 5 6d[0][0]d[0][1]3456right: nullright: null

(i=0, j=2): new Node(3); no right (last column), down → 6. Neighbors already exist; no cell is built twice.

m =1 2 34 5 6d[0][0]23456right: nullright: null

(i=0, j=1): new Node(2); right → 3, down → 5. Neighbors already exist; no cell is built twice.

m =1 2 34 5 6123456right: nullright: null

(i=0, j=0): new Node(1); right → 2, down → 4. Neighbors already exist; no cell is built twice.

m =1 2 34 5 6123456right: nullright: nullreturned ►

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 null links.
  • Keeping tail alone is enough: the head is tail.next.
  • Uses: jobs that take turns (round-robin scheduling), turn order in multiplayer games, a looping playlist.
101811tailhead = tail.next

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;
}
Why only tail?Head = tail.next, so both ends are reachable in O(1).
Keeping head as wellEvery operation would have to update two pointers; unnecessary.
Special casesEmpty: tail == null. One node: tail.next == tail.

Circularly Linked List · Step through the code

Printing a Circular List

181016tail

The list is not empty. Only tail is kept; the last node points to the head (the bottom link).

181016tailcurrent

The head is tail.next: current = 1.

181016tailcurrent

current (1) != tail (16) → loop.

181016tailcurrent

Print 1.

181016tailcurrent

current = current.next → node(8).

181016tailcurrent

current (8) != tail (16) → loop.

181016tailcurrent

Print 8.

181016tailcurrent

current = current.next → node(10).

181016tailcurrent

current (10) != tail (16) → loop.

181016tailcurrent

Print 10.

181016tail, current

current = current.next → node(16).

181016tail, current

current == tail → the loop ends (we never reach null; the condition is != tail).

181016tail, current

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 head node.
TimeO(n)
Extra spaceO(1)
Following the nodes until we get back to 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)

123456head, slow, fast

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.

123456head, slow, fast

Round 1: fast (1) and fast.next (2) are not null.

123456head, fastslow

slow moves 1 step → node(2).

123456headslowfast

fast moves 2 steps → node(3).

123456headslowfast

slow (2) ≠ fast (3) → continue.

123456headslowfast

Round 2: fast (3) and fast.next (4) are not null.

123456headslow, fast

slow moves 1 step → node(3).

123456headslowfast

fast moves 2 steps → node(5).

123456headslowfast

slow (3) ≠ fast (5) → continue.

123456headslowfast

Round 3: fast (5) and fast.next (6) are not null.

123456headslowfast

slow moves 1 step → node(4).

123456headslowfast

fast moves 2 steps → node(3).

123456headslowfast

slow (4) ≠ fast (3) → continue. fast has entered the cycle and is closing in on slow from behind.

123456headslowfast

Round 4: fast (3) and fast.next (4) are not null.

123456headslowfast

slow moves 1 step → node(5).

123456headslow, fast

fast moves 2 steps → node(5).

123456headslow, fast

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)

1nullnulltailtemp

addLast(1): create the new node.

1nullnulltailtemp

tail == null → the list is empty.

1nulltail, temp

tail = temp.

1tail, temp

tail.next = tail: the single node points to itself; the ring is closed at once.

1tail, temp

size++.

18nulltailtemp

addLast(8): create the new node.

18nulltailtemp

The list is not empty → else.

18tailtemp

temp.next = tail.next: the new node points to the head (1).

18tailtemp

tail.next = temp: the old tail (1) points to the new node.

18tail, temp

tail = temp: tail is now 8.

18tail, temp

size++.

1810nulltailtemp

addLast(10): create the new node.

1810nulltailtemp

The list is not empty → else.

1810tailtemp

temp.next = tail.next: the new node points to the head (1).

1810tailtemp

tail.next = temp: the old tail (8) points to the new node.

1810tail, temp

tail = temp: tail is now 10.

1810tail, temp

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

O(1)
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++;
}
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--;
}
Inserting at the head is inserting at the tail minus the line 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)

18105tailtemp

addFirst(5): a new node. Ring: 1 → 8 → 10 → (1), tail = 10.

18105tailtemp

The list is not empty → else.

18105tailtemp

temp.next = tail.next: 5 points to the old head (1).

18105tailtemp

tail.next = temp: 10 now points to 5 → 5 is the new head. tail doesn't change.

18105tailtemp

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()

1810tail

Ring: 1 → 8 → 10 → (1), tail = 10. Not empty.

1810tailhead

head = tail.next: the head node to delete (1).

1810tailhead

head != tail → more than one node.

1810tailhead

tail.next = head.next: 10 now points to 8; 1 has left the ring.

1810tailhead

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--;
}
181016temp, tail

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()

181016tail

removeLast(): ring 1 → 8 → 10 → 16 → (1), tail = 16. Not empty.

181016tail

tail.next != tail → not a single node.

181016tailtemp

temp = tail.next: start at the head (1).

181016tailtemp

node(1).next = 8 ≠ tail → advance.

181016tailtemp

temp = temp.next → node(8).

181016tailtemp

node(8).next = 10 ≠ tail → advance.

181016tailtemp

temp = temp.next → node(10).

181016tailtemp

node(10).next == tail → temp is at the second-to-last node.

181016tailtemp

temp.next = tail.next: 10 points to the head (1); 16 has left the ring.

181016tail, temp

tail = temp: tail is now 10.

181016tail, temp

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()

1810tail

Ring 1 → 8 → 10 → (1), tail = 10, head = tail.next = 1. Three jobs take turns on the processor.

1810tail

Round 1: the job at the head, 1, is served (printed).

1810tail

rotate(): tail = tail.next → tail = 1. No link changes, one pointer moves: O(1). New head: 8.

1810tail

Round 2: the job at the head, 8, is served (printed).

1810tail

rotate(): tail = tail.next → tail = 8. No link changes, one pointer moves: O(1). New head: 10.

1810tail

Round 3: the job at the head, 10, is served (printed).

1810tail

rotate(): tail = tail.next → tail = 10. No link changes, one pointer moves: O(1). New head: 1.

1810tail

Round 4: the job at the head, 1, is served (printed).

1810tail

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?

array (contiguous)1010008100411008111012linked list (scattered)108111
CriterionArrayLinked list
Access the i-th itemO(1): compute the addressO(n): walk from the head
Insert / delete at the frontO(n): shiftingO(1)
Insert after a known positionO(n)O(1): two links
Sizefixed; growing costs an O(n) copydynamic; one new per insertion
Overhead / cacheunused capacity; cache-friendlya 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

No empty-list checkhead.data while head is null → NullPointerException.if (head == null) return;
Linking in the wrong orderIf head changes first, the old list is lost.newNode.next = head; head = newNode;
Advancing head during a traversalAfter printing, the list is unreachable.Node temp = head;
Forgetting tailAfter the only node is deleted, tail still points to it.if (head == null) tail = null;
One direction in a doubly linked listIf 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

OperationSingly
(head only)
Singly
(head + tail)
Doubly
(head + tail)
Circular
(tail only)
Insert at headO(1)O(1)O(1)O(1)
Insert at tailO(n)O(1)O(1)O(1)
Delete at headO(1)O(1)O(1)O(1)
Delete at tailO(n)O(n)O(1)O(n)
Search / i-th itemO(n)O(n)O(n)O(n)
Delete a known nodeO(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

For more, the simulator: Linked List Simulator (insert, delete, and search step by step). The stack and queue simulators can also be backed by a linked list: Stack · Queue

Summary

Sample Problems

  1. What does it take to make inserting at the tail of a singly linked list O(1)? Which operation is still O(n)?
  2. What happens if the two lines of addFirst are swapped (head = newNode; first)?
  3. How do you find the middle of a list in one pass, without computing its length?
  4. How can you tell whether a singly linked list has a cycle (the last node linked back to an earlier one)?
  5. What does it cost to delete the tail node of a doubly linked list? Why is it different for a singly linked list?
  6. Why does a circular list keep tail rather than head?
Show answers
  1. A tail pointer. Deleting at the tail stays O(n) (we cannot step back to the previous node).
  2. The new node points to itself (newNode.next = newNode) and the old list is lost.
  3. Slow (1 step) and fast (2 steps) pointers: when fast reaches the end, slow is in the middle.
  4. The same two pointers (Floyd): if fast reaches null there is no cycle; if it catches up with slow, there is one.
  5. O(1): tail = tail.prev. In a singly linked list, reaching the previous node means walking from the head: O(n).
  6. Head = tail.next; one pointer gives O(1) access to both ends.

Summary

Exercises

  1. In the list 3 → 5 → 7, what is the list after head.next = head.next.next;? What happens to 5?
  2. What does int mystery(Node d) { return d == null ? 0 : d.data + mystery(d.next); } return for 2 → 4 → 6?
  3. How do you find the k-th item from the end of a singly linked list in one pass, without knowing its length?
  4. In a doubly linked list with sentinels, how many link assignments does inserting into an empty list take? Why is no if needed?
  5. Circular list 1 → 8 → 10 (tail = 10). After two calls to rotate(), which item is at the head?
  6. How many comparisons and swaps does sort() make on the list 3 → 1 → 2?
Answers / hints
  1. 3 → 7; if no reference to 5 remains, the garbage collector reclaims it.
  2. 12: a recursive sum; O(n) time, O(n) call stack.
  3. Two pointers: fast goes k steps ahead, then both move together; when fast is null, slow is the answer.
  4. 4 (newNode.prev, newNode.next, pred.next, succ.prev); the sentinel neighbors always exist.
  5. 10 (tail moves to 1, then to 8; head = tail.next).
  6. 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.

The End

Chapter 5: Linked Lists
Next deck: Chapter 6: The List ADT and Java Collections · Study questions · Simulators: Linked List Simulator, Doubly Linked List Simulator, Circular Linked List Simulator · Glossary
1 / 1 Sercan KÜLCÜ. All rights reserved.