priyatham
priyatham

Reputation: 49

Implementation of Queue using linked list code is returning null pointer exception

I am trying to implement Queue using Linked list in java from scratch without using LinkedList class. But, the code is returning null pointer exception. Please correct me if i am wrong. The output i am getting is 1 2 4 5 then null pointer exception.

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

Upvotes: 0

Views: 76

Answers (1)

Malt
Malt

Reputation: 30335

Your disp() method changes the value of first. Instead of iterating using first and changing its value, iterate using a temporary reference:

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
    }
}

Upvotes: 2

Related Questions