0

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

1 Answer 1

2

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.