DSA Series Day 18 Reverse Linked List in Java, Python and Rust

DSA Series Day 18: Reverse Linked List in Java, Python and Rust

Reverse Linked List is Day 18 of the Tekraze DSA series, and it moves us from stacks and queues into linked lists. It is one of the first pointer puzzles most people meet in interviews. You get the head of a singly linked list and send it back flipped, so the last node becomes the new head.

Also Read: Implement Queue using Stacks, Day 17, which closed our stacks and queues chapter.

Also Read: DSA Series Day 22: Reorder List in Java, Python and Rust

What is the Reverse Linked List problem?

Given the head of a singly linked list, reverse the list and return the new head. Each node holds a value and a pointer to the next node, and you may change those pointers as you like. On LeetCode this is problem 206.

text

Input:  1 -> 2 -> 3 -> 4 -> 5
Output: 5 -> 4 -> 3 -> 2 -> 1

Input:  1 -> 2
Output: 2 -> 1

Input:  empty list
Output: empty list

How should you think about Reverse Linked List in plain words?

Each node only knows the next one. To flip the list, you walk through it once and point each node’s next back at the node you just left.

Two side by side diagrams comparing array copy and in place pointer rewiring to reverse linked list
DSA Series Day 18: Reverse Linked List in Java, Python and Rust 6

As you go, keep three names in mind: the previous node, the current node, and the next node. Saving the next node is what stops you from losing the rest of the list.

What does the brute force approach to Reverse Linked List look like?

Walk the list once and copy every value into an array. Then walk it again and write those values back in reverse order. You never change a pointer, only the numbers stored in the nodes.

python

def reverse_list_brute(head):
    vals = []
    curr = head
    while curr:
        vals.append(curr.val)
        curr = curr.next
    curr = head
    for v in reversed(vals):
        curr.val = v
        curr = curr.next
    return head

The brute force way to solve Reverse Linked List is easy to follow and it works. The cost is extra O(n) memory for the array, and it does not help if you are asked to reverse the nodes themselves rather than copy values.

How do you reverse a linked list in the optimal way?

The optimal way to solve Reverse Linked List is to use three pointers and rewire the list in place. Start with prev as null and curr as the head. Save curr.next, point curr.next at prev, then slide prev and curr one step forward. When curr runs off the end, prev is the new head, and the old head now points at null, so it is the tail.

Time is O(n) because each node is visited once. Space is O(1) because you only keep a few pointers, with no extra list or recursion stack. A recursive version is tidy, but it uses O(n) call stack space, so the iterative walk is the one most interviewers want. For a refresher on how we talk about these bounds, see our Big O helper post.

Two side-by-side diagrams comparing array copy and in-place pointer rewiring to reverse a linked list.
DSA Series Day 18: Reverse Linked List in Java, Python and Rust 7

Java solution for Reverse Linked List

Java has no built-in singly linked node that fits this problem, so we define a small ListNode class ourselves.

java

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) { this.val = val; }
}

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    static ListNode build(int[] vals) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        for (int v : vals) {
            tail.next = new ListNode(v);
            tail = tail.next;
        }
        return dummy.next;
    }

    static int[] toArray(ListNode head) {
        int n = 0;
        for (ListNode c = head; c != null; c = c.next) n++;
        int[] out = new int[n];
        int i = 0;
        for (ListNode c = head; c != null; c = c.next) out[i++] = c.val;
        return out;
    }

    static void check(int[] input, int[] expected, String name) {
        int[] got = toArray(new Solution().reverseList(build(input)));
        if (got.length != expected.length) {
            throw new AssertionError("Failed: " + name + " length");
        }
        for (int i = 0; i < expected.length; i++) {
            if (got[i] != expected[i]) {
                throw new AssertionError("Failed: " + name + " at " + i);
            }
        }
    }

    public static void main(String[] args) {
        check(new int[]{1, 2, 3, 4, 5}, new int[]{5, 4, 3, 2, 1}, "five");
        check(new int[]{1, 2}, new int[]{2, 1}, "two");
        check(new int[]{1}, new int[]{1}, "one");
        check(new int[]{}, new int[]{}, "empty");
        check(new int[]{1, 2, 3}, new int[]{3, 2, 1}, "three");
        check(new int[]{-1, 0, 1}, new int[]{1, 0, -1}, "neg");
        System.out.println("All Java tests passed");
    }
}

Python solution for Reverse Linked List

The ListNode | None type hint needs Python 3.10 or newer. On older versions, drop the hints or use Optional[ListNode].

python

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


def reverse_list(head: ListNode | None) -> ListNode | None:
    prev = None
    curr = head
    while curr:
        nxt = curr.next
        curr.next = prev
        prev = curr
        curr = nxt
    return prev


def build(vals):
    dummy = ListNode(0)
    tail = dummy
    for v in vals:
        tail.next = ListNode(v)
        tail = tail.next
    return dummy.next


def to_list(head):
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out


if __name__ == "__main__":
    cases = [
        ([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]),
        ([1, 2], [2, 1]),
        ([1], [1]),
        ([], []),
        ([1, 2, 3], [3, 2, 1]),
        ([-1, 0, 1], [1, 0, -1]),
    ]
    for inp, expected in cases:
        assert to_list(reverse_list(build(inp))) == expected
    print("All Python tests passed")

Rust solution for Reverse Linked List

Rust lists use Option<Box<ListNode>>, and Option::take lets us pull the next node out safely. If linked lists in Rust feel odd, the free book Learning Rust With Entirely Too Many Linked Lists explains why.

rust

#[derive(Debug, PartialEq, Eq)]
struct ListNode {
    val: i32,
    next: Option<Box<ListNode>>,
}

impl ListNode {
    fn new(val: i32) -> Self {
        ListNode { val, next: None }
    }
}

fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut prev = None;
    let mut curr = head;
    while let Some(mut node) = curr {
        let next = node.next.take();
        node.next = prev;
        prev = Some(node);
        curr = next;
    }
    prev
}

fn build(vals: &[i32]) -> Option<Box<ListNode>> {
    let mut head = None;
    for &v in vals.iter().rev() {
        let mut node = Box::new(ListNode::new(v));
        node.next = head;
        head = Some(node);
    }
    head
}

fn to_vec(mut head: Option<Box<ListNode>>) -> Vec<i32> {
    let mut out = Vec::new();
    while let Some(node) = head {
        out.push(node.val);
        head = node.next;
    }
    out
}

fn check(input: &[i32], expected: &[i32]) {
    assert_eq!(to_vec(reverse_list(build(input))), expected);
}

fn main() {
    check(&[1, 2, 3, 4, 5], &[5, 4, 3, 2, 1]);
    check(&[1, 2], &[2, 1]);
    check(&[1], &[1]);
    check(&[], &[]);
    check(&[1, 2, 3], &[3, 2, 1]);
    check(&[-1, 0, 1], &[1, 0, -1]);
    println!("All Rust tests passed");
}

Each program tests the classic 1, 2, 3, 4, 5 list, a two node list, a single node, an empty list, a three node list, and a list with a negative number.

What are the tips and tricks for an easy Reverse Linked List solution?

  • Spot the pattern. When a problem asks you to change the shape of a singly linked list, think about walking once and rewiring next as you go.
  • Save the next node first. The moment you overwrite curr.next, the rest of the list is gone unless you stored it.
  • Start prev as null. That turns the old head into the new tail in the first step, with no extra cleanup.
  • Return prev, not head. After the loop, head still names the old first node, which is now the tail.
  • Draw three nodes on paper. A list of 1, 2, 3 is enough to see every pointer move before you type a line.
  • Mention both versions in interviews. Describe the recursive version, then say you prefer the iterative walk because it uses O(1) extra space. Empty lists and single nodes fall out of the same loop with no special cases.

What are the common mistakes in Reverse Linked List?

  • Forgetting to save curr.next before rewiring it, which drops the rest of the list.
  • Returning the original head instead of prev.
  • Writing a recursive solution and calling the extra stack space O(1).
  • Adding special cases for empty or single node lists that the main loop already handles.
  • Building a cycle by pointing a node back at itself, then looping forever while printing the answer.

Where is the Reverse Linked List pattern used in the real world?

In place reversal shows up whenever you store a chain of records in one direction and later need them the other way. Examples include walking a newest first event log from oldest to newest, or rebuilding a path when each node only points to its parent.

The same idea helps with flipping a stretch of a list in problems like Reverse Linked List II. The three pointer walk is also the base for reversing groups of k nodes and for some in place list partitions.

Which earlier posts in the series should you read?

Start with Day 1, Two Sum for hash map basics and Day 2, Best Time to Buy and Sell Stock for tracking a running minimum. Days 3 to 5 build the counting toolkit, Days 6 to 9 cover two pointers, and Days 10 to 12 walk through sliding window.

The stacks and queues chapter runs from Day 13, Valid Parentheses to Day 17, Implement Queue using Stacks. Keep our data structures cheat sheet handy to compare linked lists with arrays, stacks and queues. For a general overview, the linked list entry on Wikipedia is a solid reference.

Also Read: DSA Series Day 19: Merge Two Sorted Lists in Java, Python and Rust | DSA Series Day 20: Linked List Cycle in Java, Python and Rust | DSA Series Day 21: Remove Nth Node From End of List in Java, Python and Rust

Final thoughts

Grab a pen and reverse a three node list by hand, writing down prev, curr and next after each step. Once you can do Reverse Linked List by hand without looking, you can code the loop in any language.

Frequently asked questions

What is the Reverse Linked List problem?

You are given the head of a singly linked list and you reverse the order of the nodes, then return the new head.

How do you reverse a linked list in place?

Walk the list with three pointers. Save the next node, point the current node back at the previous one, then move previous and current forward until you reach the end.

What is the time and space complexity of Reverse Linked List?

The iterative solution runs in O(n) time and O(1) extra space. A recursive solution is also O(n) time, but it uses O(n) stack space.

Should you solve Reverse Linked List with recursion or with a loop?

Both work. The loop is usually preferred in interviews because it uses constant extra space and makes the pointer updates easier to talk through.

What edge cases should you test in Reverse Linked List?

An empty list, a single node, two nodes, a longer list, and values that are not a simple 1 to n sequence, such as negatives or duplicates.

Content Protection by DMCA.com
Spread the love
Scroll to Top
×