August 27, 2026

Everything About Linked List With Python Code and HackerRank/LeetCode Solutions

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.

  1. Singly linked list basics
  2. Insert and delete
  3. Traverse and reverse
  4. Two-pointer patterns (middle, cycle)
  5. Merge two sorted lists
  6. 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.

Kindson Munonye

Kindson Munonye is a software engineer and technical author covering machine learning, statistics, REST APIs, Python, and software engineering. He publishes free tutorials on The Genius Blog and live classes on Alkademy. GitHub · LinkedIn · About · Alkademy

View all posts by Kindson Munonye →
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted