This is my program for stack implementation using linked list. But I keep getting a java.lang.NullPointerException
at line number 31, i.e. the pop
function. Why is this happening and how can I correct it?
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();
}
}