在此代码中,仅显示第一个第二个节点和新节点的数据,但我想要所有节点的数据。
package linkedlispack;
public class InsertLast {
Node head;
static class Node{
int data;
Node next;
Node(int d){
data=d;
next=null;
}
}
public void printlist()
{
Node n = head;
while(n!=null){
System.out.println(n.data+"");
n=n.next;
}
}
public void push(int new_data){
Node new_node=new Node(new_data);
if(head==null){
head=new Node(new_data);
return;
}
new_node.next=null;
Node last=head;
while(last!=null){
last=last.next;
last.next=new_node;
return;
}
直到创建最后一个节点
}
public static void main(String[] args) {
// TODO Auto-generated method stub
InsertLast list=new InsertLast();
list.head=new Node(4);
Node second=new Node(10);
这里是第三个和第四个节点
Node third=new Node(12);
Node fourth=new Node(20);
list.head.next=second;
second.next=third;
third.next=fourth;
list.push(15);
list.printlist();
}
}
输出显示 4 10 15 。但我想要输出 4 10 12 20 15
最佳答案
您的问题在于您将下一个元素分配给列表外部创建的节点。你必须插入元素。如果您在外部创建它们而不是推送它们,则必须使用对象列表来指向它们。你在这里做了:
list.head.next=第二个;
如果你想继续将元素链接到列表,请使用push方法,或者你必须使用大量的next来手动完成,如下所示:list.head.next.next.next=new Node(element)
但如前所述,这里建议使用push方法。
关于java - 当我运行此代码时,仅显示两个节点的数据和新节点的数据,但不显示第三个和第四个节点的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44376418/