2015-05-31 2 views
0

Это моя программа для реализации стека с использованием связанного списка. Но я продолжаю получать java.lang.NullPointerException в строке 31, то есть функцию pop. Почему это происходит и как я могу его исправить?Исключение стека Null Pointer Exception

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(); 
    } 
} 

ответ

1

Обратите внимание, что после вызова метода printStack() первым является нулевым

Я хотел бы сделать копию, а затем итерацию.

public void printStack() 
{ 
    Node copy = first; 
    while(copy!=null) 
    { 
     System.out.println(copy.item); 
     copy = copy.next; 
    } 
}