这是我使用链表实现堆栈的程序。但我一直在第31行获得java.lang.NullPointerException
,即pop
函数。为什么会发生这种情况,我该如何纠正呢?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class StackImplementtionLinkedList
{
private Node first= null;
private class Node
{
String item;
Node next;
}
public boolean isEmpty()
{
return first==null;
}
public void push(String item)
{
Node old= first;
first= new Node();
first.item= item;
first.next= old;
}
public String pop()
{
String item= first.item;
first= first.next;
return item;
}
public void printStack()
{
while(first!=null)
{ System.out.println(first.item);
first= first.next;
}
}
public static void main(String[] args) throws FileNotFoundException
{
StackImplementtionLinkedList stack= new StackImplementtionLinkedList();
String filename= "myfile.txt";
File textfile= new File(filename);
Scanner input= new Scanner(textfile);
while(input.hasNextLine())
{
String line= input.nextLine();
stack.push(line);
}
input.close();
stack.printStack();
String popped= stack.pop();
System.out.println(popped+ " is the popped item.");
popped= stack.pop();
System.out.println(popped+ " is the popped item.");
stack.printStack();
}
}
答案 0 :(得分:1)
请注意,在调用方法printStack()之后,首先是null
我会复制然后重复。
public void printStack()
{
Node copy = first;
while(copy!=null)
{
System.out.println(copy.item);
copy = copy.next;
}
}