LearnFrenzy
Sign in Take a free test

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

Middle node with slow and fast pointers Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 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 build(int n) {
        Node head = null;
        for (int i = n; i >= 1; i--) head = new Node(i * 10, head);
        return head;
    }

    static int middle(Node head) {
        Node slow = head, fast = head;
        while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; }
        return slow.val;
    }

    public static void main(String[] args) {
        System.out.println(middle(build(5)) + " " + middle(build(6)) + " " + middle(build(1)));
    }
}
  • A 30 30 10
  • B 20 30 10
  • C 30 40 10 Correct
  • D 30 40 0
Correct Answer: Option C

With an even length the loop stops on the second of the two middle nodes (40 of 10…60).

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