← Back to libraryQuestion 103 of 273
⌨️Java CodingAdvanced

Reverse a Singly Linked List

📌 Definition:

Reverse the direction of a singly linked list so the last node becomes the head.

📖 Detailed Explanation:

Iterate with three references (prev, current, next): remember current.next, point current.next back to prev, then advance prev and current. When current becomes null, prev is the new head. O(n) time, O(1) space. A recursive version also exists but uses O(n) stack.

💻 Solutions:
static class Node { int val; Node next; Node(int v){ val = v; } }

public static Node reverse(Node head) {
    Node prev = null, curr = head;
    while (curr != null) {
        Node next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}
class Node { constructor(v) { this.val = v; this.next = null; } }

function reverse(head) {
  let prev = null, curr = head;
  while (curr) {
    const next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }
  return prev;
}
class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

def reverse(head):
    prev, curr = None, head
    while curr:
        curr.next, prev, curr = prev, curr, curr.next
    return prev
🔑 Key Points:
  • Three pointers: prev, current, next
  • Save next before rewiring current.next
  • prev is the new head at the end
  • Iterative is O(n) time, O(1) space
🌍 Real-World Example:

Linked-list reversal is a rite-of-passage pointer-manipulation problem and underlies operations like reversing sublists and detecting/undoing sequences.

🎯 Scenario-Based Interview Question:

A candidate sets curr.next = prev before saving curr.next. What breaks?