繁体   English   中英

在Java中打印链表的元素

[英]Printing elements of a linked list in java

我正在尝试在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);**
        }
    }
}
}

交换这两个语句。 在继续下一个节点之前,先打印数据:

System.out.println(current.data);
current=current.next;

并将while条件从current.next!=null更改为while current!=null因为current.next()对于最后一个Node将为null,因此将不打印

另外,您还要在append方法中两次添加1st元素。 将其更改为以下内容:

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

您有两个错误。

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

if(head==null){
    head=new Node(data);
} 

但随后您继续并再次添加。

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

while(current != null) {

而不是检查current.next

在您的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
}

因此,您的链表实际上包含第一个元素两次。 此后不会发生,因为该列表已经存在。

您应该在head = new Node(data)之后添加return ,或者使用else语句:

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

暂无
暂无

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

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