1

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();
    }
}
ZygD
  • 22,092
  • 39
  • 79
  • 102

1 Answers1

1

Notice that after calling method printStack() first is null

I would make a copy and then iterate.

public void printStack()
{
    Node copy = first;
    while(copy!=null)
    {   
        System.out.println(copy.item);
        copy = copy.next;
    }
}
Michu93
  • 5,058
  • 7
  • 47
  • 80