【发布时间】:2018-12-16 18:25:51
【问题描述】:
我正在尝试在 java 中实现链表。在我的主类中,我从用户那里得到一些整数并将它们放在一个链表中,然后打印出我的链表元素。到目前为止一切正常,但是我认为在我的主课中,首先打印出每个元素的数据然后继续下一个元素是有意义的。当我这样做时,它不会打印我列表的最后一个元素,但它会打印第一个元素两次。我决定先移动到下一个元素,然后打印前一个元素的数据,它工作得很好!!!谁能解释一下原因?(查看我的代码的最后两行)。
public class Node {
Node next;
int data;
public Node(int data){
this.data=data;
}
}
我的链表类:
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);**
}
}
}
}
【问题讨论】: