I am trying to make it dequeue the front node and print it out, however I am getting the following error:
Exception in thread "main" java.lang.NullPointerException
at MyQueue.toString(MyQueue.java:25)
at TestQueue.main(TestQueue.java:13)
From the TestQueue
class, I am expecting the outputs 1 then after dequeueing 1 again, then finally 2 from the second toString
call.
public class TestQueue {
public static void main(String[] args) {
MyQueue<String> qStr = new MyQueue();
qStr.enqueue("1");
qStr.enqueue("2");
qStr.enqueue("3");
qStr.enqueue("4");
qStr.enqueue("5");
qStr.toString(qStr.front);
qStr.dequeue();
qStr.toString(qStr.front);
}
}
public class MyQueue<T>{
MyNode<T> back;
MyNode<T> front;
public MyQueue(){
back = null;
front = null;
}
public void enqueue(T payload) {
if(back == null) {
MyNode<T> firstnode = new MyNode<T>(payload);
back = firstnode;
front = firstnode;
}
else {
MyNode<T> addtoback = new MyNode<T>(payload, back.next, null);
back = addtoback;
}
}
public String toString(MyNode<T> x) {
System.out.println(x.payload);
if(x.payload == null) {
return "";
}
else{
return (String) x.payload;
}
}
public void dequeue() {
if (isEmpty()) {
throw new RuntimeException("Queue underflow");
} else if (front == back) {
T payload1 = front.payload;
front = null;
back = null;
System.out.println(payload1);
}
T payload1 = front.payload;
front = front.previous;
System.out.println(payload1);
}
public Boolean isEmpty() {
if(back==null) {
return true;
}
return false;
}
public int size() {
MyNode<T> k = back;
if(isEmpty()||k.next==null) {
return 0;
}
k = k.next;
return 1+size();
}