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

Java 尝试使用while循环打印LinkedList时出现无限循环,java,loops,linked-list,infinite,Java,Loops,Linked List,Infinite,idk如果有人根据我在这里给出的代码理解我的问题,那么为了使用while循环正确打印LinkedList中的所有值,我应该做什么或添加什么 import java.util.*; public class testMain { public static void main(String[] args){ myLinked a = new myLinked(); a.insertAtFront(1);

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

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());
        }
    }
}
这是我的“我的链接”代码,我很确定没有错误。也许吧?不过我还是把它留在这儿


我是这里的初学者,非常感谢你的帮助 这是因为
last.data
始终等于1。
a.current.next!=null

循环中没有任何更改。执行
a.getNext()
不会改变
a
,因此如果
a.last.data!=null
第一次是真的,它将永远是真的(因此,无限循环)。总之,
a
是您的列表,所以您永远不希望它更改。您需要另一个变量,可以在列表中逐项切换。我明白了,谢谢您的帮助!:我明白了…谢谢!

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;
        }
    }
}


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