单链接列表。
执行情况:
//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.为什么?
我在哪里犯错误?
发布于 2016-11-27 10:08:25
while(root!=null){
root=root.next;
}
temp=new Node(data);
root=temp;这里:root一次是NULL。在循环之后,您不会在链的最后一个元素分配下一个元素。您不会在链中执行任何操作,因为root指向一个NULL值,并且不引用链中的一个元素。
此外,它没有意义为一个方法参数赋值,因为当方法退出时,它没有被考虑。
如果要在节点链的末尾添加Node,则应将代码替换为:
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;无论如何,一个更简单的解决方案是在您的类中有一个字段来存储链的最后一个节点。迭代所有元素以在末尾添加一个元素并不是很有效。
https://stackoverflow.com/questions/40827659
复制相似问题