我正在用Java编写一个堆栈程序。 在代码中,push函数导致空指针异常。 我想节点没有被创建。请指教。 提前致谢
//Stack_using_ll is a stack implementation using linked list
public class Stack_using_ll{
private Node first;
private int count;
private class Node {
private String str;
private Node next;
}// Node has a value and reference
public void push(String item){
Node old_first = first;
first = new Node();
first.str = item;
first.next = old_first.next;
//first = node;
count++;
}//Inserts a new node
public String pop(){
String str_pop = first.str;
first = first.next;
count--;
return str_pop;
}//pops the string out of the stack
public boolean is_empty(){
if(first == null)
return true;
else
return false;
}//check if the stack is empty
public static void main(String[] args){
Stack_using_ll stack = new Stack_using_ll() ;
stack.push("Jeans");
System.out.println("There are " + stack.count + " elements in stack");
}
}//End of class Stack_using_ll
-------------我得到的输出如下--------------------------- -
java.lang.NullPointerException
at Stack_using_ll$Node.access$2(Stack_using_ll.java:7)
at Stack_using_ll.push(Stack_using_ll.java:14)
at Stack_using_ll.main(Stack_using_ll.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
答案 0 :(得分:1)
在您的代码中:
public class Stack_using_ll{
private Node first;
private Node first
仅声明对名为“first”的节点的引用,它不会创建节点的实例供其引用。
因此,当您稍后将first
分配给oldFirst
时,您正在分配null
,尝试访问NPE中的null成员
public void push(String item){
Node old_first = first;
first = new Node();
first.str = item;
first.next = old_first.next; <- NPE here
答案 1 :(得分:0)
first
在开头为空,所以当您执行:old_first = first
时,old_first变为空,因此old_first.next
会为您提供异常。
<强>解决方案:强>
public void push(String item){
Node old_first = first;
first = new Node();
first.str = item;
if(old_first!=null)
first.next = old_first.next;
...}
答案 2 :(得分:0)
在main方法中,您创建一个新的Stack_using_ll对象,这会创建任何成员变量,但是您永远不会给first
一个值(例如在构造函数中),因此它保持为空。
private Node first; //<--- first is null here and you use the blank constructor, so it is never given a non null value
然后在主方法中调用stack.push("Jeans");
,尝试使用first
,但first
为空,因此例外。
public void push(String item){
Node old_first = first; //<-- the initial null is preserved here
first = new Node();
first.str = item;
first.next = old_first.next; //<-- you attempt to use the preserved null here
//first = node;
count++;
}
答案 3 :(得分:0)
问题是第一次推送到对象时的空指针(因为第一项是null并且你试图得到它的.next
见下面的修正:(在推送功能中)
public void push(String item){
Node old_first = first;
first = new Node();
first.str = item;
//first time old_first is null!
if (old_first != null){
first.next = old_first.next;
}
//first = node;
count++;
}