Easy Linked Lists ⭐ Core Data Structure

Reverse a Linked List — Iterative & Recursive (Python, C, JS)

Problem Statement

Given the head of a singly linked list, reverse the list and return the reversed list's head.

Example
Input: head = [1 -> 2 -> 3 -> 4 -> 5]
Output: [5 -> 4 -> 3 -> 2 -> 1]
Time Complexity
O(n)
Space Complexity
O(1)

The Intuition

Three-pointer iterative — maintain prev (None), curr, and temp_next. Flip curr.next = prev, then advance both pointers forward.

Solution Code

def reverseList(head):
    prev = None
    curr = head
    while curr:
        nxt = curr.next
        curr.next = prev
        prev = curr
        curr = nxt
    return prev
struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode *prev=NULL, *curr=head, *nxt=NULL;
    while (curr) {
        nxt = curr->next;
        curr->next = prev;
        prev = curr;
        curr = nxt;
    }
    return prev;
}
function reverseList(head) {
    let prev = null, curr = head;
    while (curr) {
        const nxt = curr.next;
        curr.next = prev;
        prev = curr;
        curr = nxt;
    }
    return prev;
}

Frequently Asked Questions

Q: Why store curr.next in a temp variable?
Because you overwrite curr.next when flipping the pointer, losing access to the rest of the list without that temporary save.

Practice These Problems in a Real Curriculum

DoxaTech Hub's 10-month programme covers Data Structures, Algorithms, Python, C, SQL, and Full-Stack Development through 40 weeks of real, graded projects.

Get Started → More Problems