我正在用Java编写一个堆栈程序。在代码中,推送函数导致空指针异常。我猜该节点没有被创建。请指教。提前致谢
//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)