使用链表代码实现Queue返回空指针异常

时间:2017-05-27 18:10:28

标签: java data-structures linked-list stack

我试图在不使用LinkedList类的情况下从头开始在java中使用Linked list实现Queue。但是,代码返回空指针异常。如果我错了,请纠正我。我得到的输出是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();
         }
    }

1 个答案:

答案 0 :(得分:2)

您的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 } } 进行迭代并更改其值,而是使用临时引用进行迭代:

{{1}}