Video in progress
Reverse a singly linked list.
With three references: prev, cur and next. At each step I point cur.next at prev and move all three one step forward. At the end prev becomes the new head. O(n) time, O(1) memory.
📖 Answer
static class Node {
int val;
Node next;
Node(int val) { this.val = val; }
}
static Node reverse(Node head) {
Node prev = null, cur = head;
while (cur != null) {
Node next = cur.next; // save it so we don't lose it
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
The most common mistake is writing cur.next = prev without saving next. At that moment the link to the rest of the list is cut.
There is a recursive variant too:
static Node reverseRec(Node head) {
if (head == null || head.next == null) return head;
Node newHead = reverseRec(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
It's elegant, but it takes O(n) stack, so on a long list you get a StackOverflowError. It's good to know both in an interview, but give the iterative one as your main answer.
Sign up to mark studied questions and save your progress.