A queue is implemented using a singly linked list.
The variable back "points" at the first node in the linked list. New elements are added (enqueued) at the back.
The variable front "points" at the last node in the linked list. Elements are removed (dequeued) from the front.
This implementation is the opposite of a usual queue where the back is the last node and the front is the first node. I know this is not a good way of implementing a queue, but it is good practice coding with linked lists.
I have written the enqueue() function however am not sure what I am doing wrong with the dequeue(). I have to get to the front, which is the last node, to dequeue it. So I must traverse the Node to remove and return the item at the front of the queue.
//Node stuff
private Node front, back;
static class Node {
public Node (char item, Node next) { this.item = item; this.next = next; }
public char item;
public Node next;
}
dequeue function: needs work
public char dequeue() {
char item;
if (back.item == front.item) {
item = front.item;
back = null;
}
for (Node tmp = back; tmp != null; tmp= tmp.next){
if (tmp.next == null){
item = tmp.item;
back.next = null;
}
}
return item;
}
I created a char to store the value of the item I am going to remove...My problem is removing the last node from the list. I am not sure how to do it without getting a Null Pointer Exception. Any input would be much appreciated!