Updated August 2026 — full tutorial restored for this URL.
This is a practical linked list guide in Python: structure, core operations, and patterns that show up on HackerRank / LeetCode. Also see How to Reverse a Linked List.
- Singly linked list basics
- Insert and delete
- Traverse and reverse
- Two-pointer patterns (middle, cycle)
- Merge two sorted lists
- Practice checklist
1. Singly linked list basics
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
Arrays give O(1) index access; linked lists give O(1) insert/delete at a known node (after you find it).
2. Insert and delete
def push_front(self, val):
self.head = Node(val, self.head)
def delete_val(self, val):
dummy = Node(0, self.head)
cur = dummy
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
break
cur = cur.next
self.head = dummy.next
Dummy nodes simplify edge cases at the head.
3. Traverse and reverse
def to_list(head):
out = []
while head:
out.append(head.val)
head = head.next
return out
def reverse(head):
prev = None
while head:
nxt = head.next
head.next = prev
prev, head = head, nxt
return prev
4. Two-pointer patterns (middle, cycle)
def middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
Floyd’s cycle detection is a classic interview question (LeetCode 141).
5. Merge two sorted lists
def merge(l1, l2):
dummy = Node(0)
cur = dummy
while l1 and l2:
if l1.val <= l2.val:
cur.next, l1 = l1, l1.next
else:
cur.next, l2 = l2, l2.next
cur = cur.next
cur.next = l1 or l2
return dummy.next
6. Practice checklist
- Reverse list / reverse in k-groups
- Remove nth from end (two pointers)
- Detect/start of cycle
- Merge k sorted lists (heap)
- Copy list with random pointer
Draw pointers on paper before coding — most bugs are lost references, not syntax.