TExcelTAD
Home › Data Structures & Algorithms › Linked Lists Intro

Linked Lists Intro

A linked list is a chain of nodes. Each node holds a value and a reference (a "link" or "pointer") to the next node. The list itself only needs to remember the first node, the head. The last node's link is None, which marks the end.

text
head
 │
 ▼
┌────┬───┐   ┌────┬───┐   ┌────┬──────┐
│ 12 │ ●─┼──▶│ 7  │ ●─┼──▶│ 30 │ None │
└────┴───┘   └────┴───┘   └────┴──────┘

Unlike an array, the nodes do not have to sit next to each other in memory. That makes some operations cheap (inserting at the front never shifts anything) and others expensive (there is no list[i]: you must walk from the head).

A node class

python · try it yourself
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None          # link to the next node, or None at the end

# build 12 -> 7 -> 30 by hand
head = Node(12)
head.next = Node(7)
head.next.next = Node(30)

current = head
while current is not None:     # the standard traversal loop
    print(current.value, end=" -> ")
    current = current.next
print("None")
12 -> 7 -> 30 -> None

The traversal loop, "start at the head, follow next until None", is the core of almost every linked list operation.

A small LinkedList class

Wrapping the head in a class gives us a clean interface. Here are the two simplest insertions:

python · try it yourself
class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None

    def prepend(self, value):          # O(1): the new node becomes the head
        self.head = Node(value, self.head)

    def append(self, value):           # O(n): walk to the last node first
        node = Node(value)
        if self.head is None:
            self.head = node
            return
        current = self.head
        while current.next is not None:
            current = current.next
        current.next = node

    def __str__(self):
        parts = []
        current = self.head
        while current:
            parts.append(str(current.value))
            current = current.next
        return " -> ".join(parts) + " -> None"

songs = LinkedList()
songs.append("Intro")
songs.append("Verse")
songs.prepend("Count-in")
songs.append("Chorus")
print(songs)
Count-in -> Intro -> Verse -> Chorus -> None

Step through the same operations on numbers, plus a search. Notice that find has to visit the nodes one by one from the head:

Linked list vs array

Operation Array (Python list) Singly linked list
Access element i O(1) O(n): walk i steps
Insert / delete at the front O(n): shift everything O(1)
Insert / delete after a known node O(n) O(1)
Append at the end O(1) average O(n), or O(1) with a tail pointer
Search for a value O(n) O(n)
Memory per element the value the value + a link

So linked lists shine when you add and remove at the front (or in the middle, once you are there) a lot, and arrays shine when you need random access.

Counting and searching

python · try it yourself
class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

def from_values(values):
    head = None
    for v in reversed(values):        # prepend in reverse to keep the order
        head = Node(v, head)
    return head

def length(head):
    count = 0
    while head:
        count += 1
        head = head.next
    return count

def find(head, target):
    index = 0
    while head:
        if head.value == target:
            return index
        head = head.next
        index += 1
    return -1

lst = from_values([12, 7, 30, 7])
print(length(lst), find(lst, 30), find(lst, 99))
4 2 -1

Where linked lists are used

  • Queues and stacks: adding and removing at the ends without shifting (Python's collections.deque is a linked list of blocks).
  • Undo history, playlists and browser history, often as doubly linked lists.
  • Hash tables with chaining: each bucket is a small linked list.
  • Graph adjacency lists and memory allocators' free lists.

Note: In Python you rarely build linked lists yourself; lists and deque are faster in practice. We build them here because the ideas (nodes, links, None as the end, pointer updates) are the foundation of trees and graphs.

Test yourself

What does the last node of a singly linked list point to?

  1. The head
  2. Itself
  3. None (null)
  4. The previous node

Why is accessing the 1000th element of a linked list slow?

  1. Nodes are larger than array slots
  2. You must follow 999 links from the head
  3. Linked lists are always sorted
  4. Python limits the list length

Which operation is O(1) for a singly linked list but O(n) for an array?

  1. Accessing by index
  2. Inserting at the front
  3. Searching for a value
  4. Finding the length without a counter