java链表。这个程序不打印8。为什么?
单链表java链表。这个程序不打印8。为什么?,java,data-structures,linked-list,singly-linked-list,Java,Data Structures,Linked List,Singly Linked List,单链表 我创建节点 添加新节点 实施: //create node class Node { int data; Node next; Node(int data) { this.data = data; next = null; } } public class LinkedList { //Add new node public static void add(Node root, int data){ Node temp; whi
//create node
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
}
}
public class LinkedList {
//Add new node
public static void add(Node root, int data){
Node temp;
while (root != null) {
root = root.next;
}
temp = new Node(data);
root = temp;
}
//print node
public static void print(Node root){
while (root != null) {
System.out.println(root.data);
root = root.next;
}
}
public static void main(String[] args) {
Node root ;
Node iter;
root = new Node(7);
iter = root;
add(iter, 8);
print(iter);
}
}
我研究数据结构。我想创建一个链表,但程序失败了。这个程序不打印8。为什么
我在哪里犯错
while(root!=null){
root=root.next;
}
temp=new Node(data);
root=temp;
此处:root
一次为NULL
。
循环之后,不在链的最后一个元素指定下一个元素。您不在链中执行任何操作,因为root
指向NULL
值,并且不引用链中的元素。此外,为方法参数赋值没有意义,因为在方法退出时不考虑它 如果要将节点添加到节点链的末端,应将代码替换为:
while(root.next !=null){
root=root.next;
}
temp=new Node(data);
root.next=temp;
你可以用更有意义的名字来写:
Node lastElement = root;
while(lastElement.next !=null){
lastElement=lastElement.next;
}
temp=new Node(data);
lastElement.next=temp;
无论如何,一个更简单的解决方案是在类中有一个字段来存储链的最后一个节点。迭代所有元素以在末尾添加元素不是很有效