LearnFrenzy
Sign in Take a free test

Data Structures in Java · Data Structures in Java Output Questions · Question 6

Reversing a linked list recursively Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links