🔗 Linked Lists

A chain of nodes connected by pointers

← Back to Algorithms

🚂 What is a linked list?

A linked list is a chain of nodes. Each node holds a piece of data and a pointer to the next node — like train cars coupled together. The last node points to None.

[ 3 | •]──>[ 7 | •]──>[ 9 | None ] head

Unlike a Python list (stored in one solid block of memory), a linked list's nodes can live anywhere — they're connected only by their pointers.

🧱 Building a Node

We use a class with two attributes: data and next.

class Node: def __init__(self, data): self.data = data self.next = None # points to nothing yet # Link them by hand a = Node(3) b = Node(7) a.next = b # 3 now points to 7 print(a.data) # 3 print(a.next.data) # 7

🚶 Walking the list (traversal)

To visit every node, start at the head and follow .next until you hit None:

current = head while current is not None: print(current.data) current = current.next # hop to the next node

⚖️ Linked list vs. array

OperationArray / listLinked list
Get by indexO(1)O(n)
Insert at frontO(n)O(1)
MemoryOne solid blockScattered nodes

💡 When to use which

Linked lists shine when you add/remove at the front a lot. Arrays win when you need fast index access. Python's built-in list is an array — but knowing linked lists helps you understand stacks, queues, and trees.

✅ What you learned

  • A linked list is nodes connected by .next pointers.
  • Each node has data and a pointer; the last points to None.
  • Traverse by following .next from the head.
  • Fast inserts at the front, but slow index access.