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