Skip to main content
Albero Academy

Linked Lists, Stacks & Queues

Pointer-based structures — singly linked lists, and the stack (LIFO) and queue (FIFO) that power so many algorithms.

Chapter 3DSA15 min readBeginner friendly
  • #DSA
  • #Linked Lists
  • #Stacks

Arrays store data by position; linked structures store data by reference — each node points to the next. That trade-off (cheap insertion, no random access) gives us linked lists, and the stack and queue that so many algorithms rely on.

Linked lists

A singly linked list is a chain of nodes, each holding a value and a pointer to the next. Inserting at the front is O(1) (no shifting), but reaching the k-th element means walking the chain — O(n):

a linked list node & traversal
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
# Build 1 → 2 → 3
head = Node(1, Node(2, Node(3)))
# Traverse
node = head
while node:
print(node.val)
node = node.next

The classic exercise — reverse a linked list — is worth memorising, as it teaches pointer manipulation:

reverse in place, O(n) time O(1) space
def reverse(head):
prev = None
while head:
nxt = head.next # save next
head.next = prev # flip the pointer
prev = head # advance
head = nxt
return prev # new head

Stacks (LIFO)

A stack is last-in, first-out — like a stack of plates. Push and pop from one end, both O(1). A plain list works as a stack:

matched brackets with a stack
def is_balanced(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack

Queues (FIFO)

A queue is first-in, first-out — like a line at a counter. Add at the back, remove from the front. Use collections.deque for O(1) at both ends (a list's pop(0) is O(n)):

a queue
from collections import deque
q = deque()
q.append("a") # enqueue at the back
q.append("b")
q.popleft() # "a" — dequeue from the front

When to use which

  • Stack — undo/redo, matching brackets, depth-first traversal, function call frames.
  • Queue — task scheduling, breadth-first traversal, buffering.
  • Linked list — when you insert/remove at the ends constantly and never need random access.

Practice

Implement: (1) reverse a linked list; (2) check if a string of brackets is balanced using a stack; (3) a simple queue with deque. These three appear constantly in interviews.

Key takeaways

  1. 01Linked lists trade O(1) end-insertion for O(n) random access — nodes point to the next.
  2. 02Reversing a linked list in place is a must-know pointer exercise.
  3. 03A stack is LIFO (push/pop one end) — brackets, undo, depth-first search.
  4. 04A queue is FIFO — use collections.deque for O(1) at both ends.
  5. 05Pick the structure by access pattern: ends-only + no indexing → linked/stack/queue.