Linked lists

Data scattered in memory, connected by pointers.

The idea

Unlike an array, a Linked List does not require a contiguous block of memory. Each "Node" holds a value and a pointer (a memory address) to the next node. This makes inserting or deleting elements at the front extremely fast (O(1)), but looking up the Nth element is slow (O(N)).

Click Play to reverse the linked list in-place.

How it works (In-place Reversal)

def reverseList(head):
    prev = None
    curr = head
    
    while curr:
        nxt = curr.next     # 1. Save the next node
        curr.next = prev    # 2. Reverse the pointer
        prev = curr         # 3. Move prev forward
        curr = nxt          # 4. Move curr forward
        
    return prev # prev is the new head