Linked List

A linked list is a linear data structure made of nodes, where each node holds a value and a reference (pointer) to the next node. Unlike arrays, elements aren't stored contiguously in memory, which makes insertion and deletion at arbitrary positions much cheaper — at the cost of O(n) random access.

Singly vs Doubly Linked Lists

Common Techniques

Time & Space Complexity

Operation Array Linked List
Access by indexO(1)O(n)
SearchO(n)O(n)
Insert at headO(n)O(1)
Insert/delete at known nodeO(n)O(1)
Space overheadO(n)O(n) + pointer per node

Illustration: Node Chain with Pointers

Linked List Illustration

C++ Example: Reverse a Singly Linked List

reverse_linked_list.cpp
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

ListNode* reverseList(ListNode* head) {
    ListNode* prev = nullptr;
    ListNode* curr = head;

    while (curr != nullptr) {
        ListNode* nextTemp = curr->next;
        curr->next = prev;
        prev = curr;
        curr = nextTemp;
    }
    return prev;
}

Python Example: Common Linked List Patterns

linked_list_patterns.py
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


# 1. Detect a cycle using fast & slow pointers (Floyd's algorithm)
def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            return True
    return False


# 2. Find the middle node using fast & slow pointers
def middle_node(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow


# 3. Merge two sorted linked lists using a dummy head
def merge_two_lists(l1, l2):
    dummy = ListNode()
    tail = dummy

    while l1 and l2:
        if l1.val <= l2.val:
            tail.next = l1
            l1 = l1.next
        else:
            tail.next = l2
            l2 = l2.next
        tail = tail.next

    tail.next = l1 if l1 else l2
    return dummy.next

Quiz

You want to detect whether a linked list contains a cycle without using extra space. Which technique is best suited?

Practice on LeetCode

Once you're comfortable with the concepts above, try solving these problems to reinforce your understanding:

← Back to DSA