Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 17 / Topic 9 of 20

Linked list

A linked list is a chain of nodes, each holding a value and a pointer to the next node - unlike Python's list, which is a contiguous array under the hood (Part 14). There is no linked-list class in the standard library for everyday use (collections.deque is usually the right tool when you want fast ends); you build one when you specifically need O(1) insert/delete once you are already at a node, without shifting anything else. Think of a treasure hunt where each clue tells you only where the next clue is - you cannot jump straight to clue 10 without walking through 1 to 9 first.

Operation Python list (array) Linked list
access by index O(1) O(n) (must walk from the head)
insert/delete at the front O(n) O(1)
insert/delete at a known node O(n) O(1)
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None
        self._tail = None             # remembered so append() stays O(1)

    def append(self, value):
        node = Node(value)
        if self.head is None:
            self.head = self._tail = node
        else:
            self._tail.next = node
            self._tail = node

playlist = LinkedList()
for song in ["Kesariya", "Tum Hi Ho", "Jai Ho"]:
    playlist.append(song)

Reversing just flips every .next pointer, O(n) time and O(1) extra space - no new list needed. A classic linked-list trick, Floyd's tortoise and hare, detects a cycle (a node that eventually points back to an earlier node) with two pointers, one moving twice as fast as the other:

def has_cycle(head):
    slow = fast = head
    while fast is not None and fast.next is not None:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:          # the fast pointer lapped the slow one
            return True
    return False

If there is no cycle, fast reaches the end and the loop stops with False; if there is a cycle, fast is bound to eventually land on the same node as slow.

Real-world example: a music player's "up next" queue is naturally a linked list - each song only needs to know what plays after it, and inserting a song in the middle of the queue does not require shifting every other song.

⚠️ Forgetting to update the old tail's .next, or losing the only reference to the rest of the chain while relinking, silently drops nodes. Always save node.next in a temporary variable before overwriting it (see reverse() in the full program).

Practice: reverse a linked list; detect a cycle with fast/slow pointers; merge two already-sorted linked lists into one sorted chain.

Practice on LeetCode - start here: Reverse Linked List · Middle of the Linked List · Merge Two Sorted Lists · Linked List Cycle · Remove Nth Node From End of List · Reorder List

Show the full practice list (17 more problems)

Core practice - gentler first:

Stretch - tougher; come back once the core feels comfortable:

Full program: examples/09_linked_list.py.

Exercise 9: Linked list — remove every occurrence of a value

Scenario: A playlist (linked list) needs every copy of one song removed, without rebuilding the whole list as a Python list. What to do: Using the Node/LinkedList classes from examples/09_linked_list.py (copy or import the pattern), write a method or function remove_value(head, value) that returns a new head with every node holding value skipped over, by relinking .next pointers. Print the playlist before and after removing "Jai Ho" from the data below (which has it twice).

Starting data:

SONGS = ["Jai Ho", "Kesariya", "Jai Ho", "Tum Hi Ho"]

Sample output:

Before: ['Jai Ho', 'Kesariya', 'Jai Ho', 'Tum Hi Ho']
After removing 'Jai Ho': ['Kesariya', 'Tum Hi Ho']
Show the solution to Exercise 9
"""Exercise 9: Linked list - remove every occurrence of a value.

Run:   python ex08.py   (macOS/Linux: python3 ex08.py)
"""

SONGS = ["Jai Ho", "Kesariya", "Jai Ho", "Tum Hi Ho"]


class Node:
    def __init__(self, value):
        self.value = value
        self.next: "Node | None" = None


def build_list(values: list) -> Node | None:
    head = tail = None
    for value in values:
        node = Node(value)
        if head is None:
            head = tail = node
        else:
            tail.next = node
            tail = node
    return head


def to_list(head: Node | None) -> list:
    items = []
    node = head
    while node is not None:
        items.append(node.value)
        node = node.next
    return items


def remove_value(head: Node | None, value) -> Node | None:
    """Return a new head with every node holding `value` skipped over.

    A dummy node in front of `head` means removing the head itself needs
    no special case: we always relink some `previous.next`.
    """
    dummy = Node(None)
    dummy.next = head
    previous = dummy
    current = head
    while current is not None:
        if current.value == value:
            previous.next = current.next      # skip it
        else:
            previous = current
        current = current.next
    return dummy.next


def main() -> None:
    head = build_list(SONGS)
    print("Before:", to_list(head))
    head = remove_value(head, "Jai Ho")
    print("After removing 'Jai Ho':", to_list(head))


if __name__ == "__main__":
    main()

💡 Hint: Use a dummy node pointing at the head so removing the head itself needs no special case; walk with a previous pointer and skip matching nodes by setting previous.next = current.next.

Search the guide