繁体   English   中英

尝试使用 while 循环打印 LinkedList 时出现无限循环

[英]Infinite loop when trying to print LinkedList using while loop

import java.util.*;

public class testMain {
    public static void main(String[] args){
        
        myLinked a = new myLinked();
        
        a.insertAtFront(1);
        a.insertAtFront(2);
        a.insertAtFront(3);
        a.insertAtFront(4);
        a.insertAtFront(5);
        
        System.out.println(a.getFirst());
        while (a.last.data != null) {
            System.out.println(a.getNext());
        }
    }
}

idk 如果有人会根据我在这里给出的代码理解我的问题,但是我应该做什么或添加什么才能使用 while 循环在 LinkedList 中正确打印所有值?


public class myLinked {
    Node first, last,current ;
   
    public myLinked(){
        
    }
    
    public void insertAtFront(Object insertItem){
        
    Node newNode = new Node(insertItem);
    if( first == null ){ 
        first = newNode;
        last = newNode;
    }else
    {
        newNode.next = first;
        first = newNode;
    }
  }
    
    public Object removeFromFront(){
        Object removeItem = null;
    if (first == null){
          return removeItem;
      }
      removeItem = first.data;
    if ( first == last){
        first = null;
        last = null;
      }else
        first = first.next;
    return removeItem;
}
    
    public void insertAtBack(Object insertItem){

    Node newNode = new Node(insertItem);
    if (first == null){ 
        first = newNode;
        last = newNode;
    }else
    {
        last.next = newNode;
        last = newNode;
    }
  }
    
    public Object removeFromBack(){
        Object removeItem = null;
      if (first == null){
          return removeItem;
      }
    removeItem = last.data;
      
      if ( first == last){
          first = null;
          last = null;
      }else
      {
          current = first;
        while (current.next != last)
            current = current.next;
            last = current;
            last.next = null;
      }
      return removeItem;
}
    
    public Object getFirst(){
        if (first == null)
            return null;
        else{
            current = first;
            return current.data;
        }
    }
    
    public Object getNext(){
        if (current == last)
            return null;
        else{
            current = current.next;
            return current.data;
        }
    }
}

所以继承人我的“myLinked”代码,我很确定没有错误..也许? 但无论如何我还是把它留在这里

我是这里的初学者,非常感谢您的帮助! <3


public class Node {
    Object data;
    Node next;
    
    Node(Object obj){
        data=obj;
    }
}

我的节点代码..这里只有 3 个我正在使用的类

这是因为last.data总是等于 1。用a.current.next != null替换while条件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM