Reputation: 115
The following code is a Queue which is supposed to add and remove integer values but the function are not working as intended. Only first two values are added and remove function shows null pointer exception. In addition, the iterator class is not iterating over the Integer values. It causes infinite loop. What is the cause?
Thank you.
Upvotes: 0
Views: 84
Reputation: 977
These two lines in the add
method seem to be creating a cycle:
front.next = previousNode;
previousNode.next = front;
The cycle here results in the infinite loop in iteration.
I think what you need is just to set the next of the previous node to the new node.
previousNode.next = front;
Also this part of the remove
method doesn't seem correct:
E n = back.element;
back = back.next;
if (back == null)
front = null;
else
back.next = null;
The problem here is that you're setting back.next
to null every time, which makes you lose the rest of the queue.
In order to fix that you just need to remove the else part, so that you keep the old next.
E n = back.element;
back = back.next;
if (back == null)
front = null;
Upvotes: 1