Jason arora
Jason arora

Reputation: 550

Output for finding middle node in a Linked List does not come as expected?

Problem:

I tried to implement a simple approach to Find the middle Element in a LinkedList but I am moving into infinite loop.

Solution: Below is my code that implements the following functionality:

public static void main(String[] args) {
  //Approach1:
 // 1 Traverse the LinkedList and find the number of Nodes
//  2 Calc the middle node in o(1) time. 
    int count=0;
    LinkedList ll=insert();
    System.out.println(ll);
    Iterator it=ll.iterator();
    while(it.hasNext()){
        count++;
        System.out.println(count);
//LinkedList ll1=(LinkedList)it.next(); 
    }
    System.out.println("The Middle Node is "+count/2);
    //Approach2:


    //Approach3


    // TODO Auto-generated method stub

}

public static LinkedList insert(){
    LinkedList ladd=new LinkedList();
    ladd.add(2);
    ladd.add(3);
    ladd.add(4);
    ladd.add(5);
    ladd.add(6);
    ladd.add(7);
    System.out.println(ladd);
    return ladd;    

}

Output shown:Infinite Loop

Expected Output:3

Upvotes: 0

Views: 39

Answers (2)

vlaxmi
vlaxmi

Reputation: 468

it.next() is never called inside the while loop. Below code prints expected output as :3

 while(it.hasNext()){
            it.next();
            count++;
            System.out.println(count);
        }

Upvotes: 0

MSD
MSD

Reputation: 1407

You missed to add it.next()

while (it.hasNext()) {
   count++;
   System.out.println(count); // LinkedList ll1=(LinkedList)it.next(); }
   it.next();
}

Upvotes: 2

Related Questions