用java打印链表的元素

用java打印链表的元素,java,singly-linked-list,Java,Singly Linked List,我正在尝试用java实现链表。在我的主类中,我从用户那里得到一些整数,并将它们放入一个链表中,然后打印出我的链表元素。到目前为止,一切都很正常,但是我认为在我的主课中,首先打印出每个元素的数据,然后转到下一个元素是有意义的。当我这样做时,它不会打印列表的最后一个元素,但会打印第一个元素两次。我决定先转到下一个元素,然后打印上一个元素的数据,它工作得很好!!!有人能解释为什么吗?(查看我代码的最后两行) 我的链表类: public class LinkedList { Node head; pu

我正在尝试用java实现链表。在我的主类中,我从用户那里得到一些整数,并将它们放入一个链表中,然后打印出我的链表元素。到目前为止,一切都很正常,但是我认为在我的主课中,首先打印出每个元素的数据,然后转到下一个元素是有意义的。当我这样做时,它不会打印列表的最后一个元素,但会打印第一个元素两次。我决定先转到下一个元素,然后打印上一个元素的数据,它工作得很好!!!有人能解释为什么吗?(查看我代码的最后两行)

我的链表类:

public class LinkedList {
Node head;

public void append(int data){
    if(head==null){
        head=new Node(data);
    }
    Node current;
    current=head;
    while(current.next!=null){
        current=current.next;
    }
    current.next=new Node(data);
}
}
我的主要班级:

public class Main {
static LinkedList linkedList =new LinkedList();
public static void main(String [] args){
    System.out.println("please enter numbers you wanna store in a linked list");
    Scanner scanner=new Scanner(System.in);
    while (scanner.hasNextInt()){
        linkedList.append(scanner.nextInt());
    }
    if (linkedList.head!=null){
        Node current;
        current=linkedList.head;
        while (current.next!=null){
            **current=current.next;
            System.out.println(current.data);**
        }
    }
}
}

交换这两条语句。在转到下一个节点之前打印数据:

System.out.println(current.data);
current=current.next;
并从
current.next更改while条件=空值
到当前值,而
当前值=null
因为最后一个节点的current.next()将为null,因此不会被打印

另外,您在
append
方法中添加了两次第一个元素。将其更改为以下内容:

public void append(int data){
    if(head==null){
        head=new Node(data);
    }
else{
    Node current;
    current=head;
    while(current.next!=null){
        current=current.next;
    }
    current.next=new Node(data);}
}

append
语句中,添加第一个元素两次:

public void append(int data){
    if(head==null){
        head=new Node(data); // <--- Added here
    }
    Node current;
    current=head;
    while(current.next!=null){
        current=current.next;
    }
    current.next=new Node(data); // <--- And then again here
}
你有两个虫子

(1) 将第一个元素添加两次。你有

if(head==null){
    head=new Node(data);
} 
但是,您可以继续并再次添加它

(2) 打印列表时,当
current.next==null
时停止-因此在到达最后一个元素之前停止。
while
循环的条件需要

while(current != null) {

当我执行此操作时,它不打印列表的最后一个元素,而是打印第一个元素两次,而不是检查
current.next

。我想知道为什么,这正是我的问题。@backslash:在纸上完成你们的代码,你们会明白的。这只是简单的逻辑。正如RealSpecic正确提到的,您在
append
方法中添加了两次元素。这并没有回答问题。你所建议的是OP最初所做的,这导致了问题。这只处理了两个bug中的一个。@DawoodibnKareem如果你是指print语句中的下一个额外bug,那么OP说这是一个“变通方法”,所以它本来就不存在。不,这根本不是我的意思。
if(head==null){
    head=new Node(data);
} 
while(current != null) {