2017-05-27 97 views
0

我想从头开始使用Java中的链接列表而不使用LinkedList类实现队列。但是,代码正在返回空指针异常。如果我错了,请纠正我。我得到的输出是1 2 4 5,然后是空指针异常。使用链接列表代码实现队列返回空指针异常

package example2; 

    class Node 
    { 
     int data; 
     Node next; 
     Node(int data) 
     { 
      this.data=data; 
     } 
    } 


    public class ex { 

     Node last=null,first=null; 

     private void push(int item) 
     { 
       if(last==null) 
       { 
        first=last=new Node(item); 

       } 
       else 
       { 
        Node n = new Node(item); 
        last.next=n; 
        n.next=null; 
        last=n; 
       } 

     } 

     private void pop() 
     { 
      first=first.next; 
     } 

     public void disp() 
     { 
      while(first!=null) 
      { 
       System.out.println(first.data); 
       first=first.next;    
      } 
     } 

     public static void main(String []args) 
     { 
      ex e=new ex(); 
      e.push(1); 
      e.push(2); 
      e.push(4); 
      e.push(5); 
      e.disp(); 
      e.pop(); 
      e.disp(); 
     } 
    } 

回答

2

您的disp()方法更改了值first。代替使用first进行迭代并更改其值,请使用临时参考进行迭代:

public void disp() { 
    Node current = first; //Start with "first" 
    while (current != null) { 
     System.out.println(current.data); 
     current = current.next; //Move "current" to next node 
    } 
}