有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于在链表中查找中间节点的java输出没有达到预期效果?

问题:

我试图实现一种简单的方法来查找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


共 (2) 个答案

  1. # 1 楼答案

    it.next()从未在while循环中调用。下面的代码将预期输出打印为:3

     while(it.hasNext()){
                it.next();
                count++;
                System.out.println(count);
            }
    
  2. # 2 楼答案

    您没有添加it.next()

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