Reverse the direction of a singly linked list so the last node becomes the head.
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.
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 prevLinked-list reversal is a rite-of-passage pointer-manipulation problem and underlies operations like reversing sublists and detecting/undoing sequences.
A candidate sets curr.next = prev before saving curr.next. What breaks?