Question 6
Back to Exercise
What is the output of the following Java program?
public class Main {
static class Node {
int val;
Node next;
Node(int val, Node next) { this.val = val; this.next = next; }
}
static Node reverse(Node head) {
if (head == null || head.next == null) return head;
Node rest = reverse(head.next);
head.next.next = head;
head.next = null;
return rest;
}
public static void main(String[] args) {
Node head = new Node(1, new Node(2, new Node(3, new Node(4, null))));
Node r = reverse(head);
StringBuilder sb = new StringBuilder();
for (Node n = r; n != null; n = n.next) sb.append(n.val);
System.out.println(sb + " " + head.val + " " + (head.next == null));
}
}
- A 4321 1 true Correct
- B 4321 4 false
- C 1234 1 false
- D 4321 1 false
Correct Answer: Option A
head still refers to the node holding 1, which is now the tail, so its next is null.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!