Skip to content

Linked Lists, Stacks, and Queues

## Intuition

Building blocks of all data structures: Linked lists, stacks, and queues are like the atoms of data structures — almost every complex data structure is built from these primitives. Linked lists give dynamic sizing, stacks enforce LIFO order, and queues enforce FIFO order.

Why it matters: Understanding these fundamentals lets you implement more complex data structures from scratch and choose the right abstraction for the job. Stacks handle undo/redo, queues handle task scheduling, and linked lists handle dynamic collections.

The key insight: Linked lists trade space for flexibility — each node wastes pointer space but gains O(1) insertion/deletion. Arrays trade flexibility for cache efficiency — contiguous memory enables O(1) access but O(n) insertion.

A singly linked list is a sequence of nodes where each node contains a value and a reference to the Next node. The list is accessed through a head pointer; traversal requires following pointers from The head.

class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def insert_at_head(head, val):
"""Insert at the head of the list. O(1)."""
return ListNode(val, head)
def insert_at_tail(head, val):
"""Insert at the tail. O(n) without tail pointer, O(1) with tail pointer."""
new_node = ListNode(val)
if head is None:
return new_node
current = head
while current.next:
current = current.next
current.next = new_node
return head
def delete_node(head, val):
"""Delete the first node with the given value. O(n)."""
if head is None:
return None
if head.val == val:
return head.next
current = head
while current.next:
if current.next.val == val:
current.next = current.next.next
return head
current = current.next
return head
  • Hashing and Hash Tables: Covers hash-based data structures that provide O(1) average-case operations compared to linear structures.
  • Sorting Algorithms: Sorting techniques that can be applied to linked lists and arrays.
  • Dynamic Programming: Explores recursive problem-solving that builds on stack and queue concepts.