Recursive Linked List Reversal
Consider the following class.
public class Reverser {
static class Node {
int val;
Node next;
Node(int v) { val = v; }
}
public static Node reverse(Node head) {
if(head == null || head.next == null) return head;
Node newHead = reverse(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head = reverse(head);
Node curr = head;
while(curr != null) {
System.out.print(curr.val + " ");
curr = curr.next;
}
}
}
What is printed when the main method is executed?
A
1 3 2
B
1 2 3
C
3 2 1
D
2 3 1
Question Leaderboard
Not enough data yet to show leaderboard.
