Jason arora Jason arora -4 years ago 76
Java Question

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

Answer Source

You missed to add it.next()

while (it.hasNext()) {
   count++;
   System.out.println(count); // LinkedList ll1=(LinkedList)it.next(); }
   it.next();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download