问题:
我试图在LinkedList中实现一个简单的方法来查找中间元素,但我正在进入无限循环。
解决方案: 下面是我的代码,它实现了以下功能:
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;
}
显示的输出:无限循环
预期产出:3
答案 0 :(得分:2)
您错过了添加it.next()
while (it.hasNext()) {
count++;
System.out.println(count); // LinkedList ll1=(LinkedList)it.next(); }
it.next();
}
答案 1 :(得分:0)
while(it.hasNext()){
it.next();
count++;
System.out.println(count);
}
。下面的代码将预期输出打印为:3
{{1}}