I'm struggling to get my head around this data structure. In my course we use the following code to implement a Queue using linked lists:
class Queue
{
private Item sentinel , tail;
public Queue () {
sentinel = new Item(0,null);
tail = sentinel;
}
public void enqueue(int value) {
tail.next = new Item(value , null);
tail = tail.next;
}
public int dequeue ()
{
int value = sentinel.next.value;
sentinel.next = sentinel.next.next;
return value;
}
}
I don't see how this should work, when we call the constructor method we have sentinel[0|null] and then we let tail=sentinel, so tail[0|null]. By calling .enqueue(x), we get the following:
[0|pointer to tail], tail[x|null]
If we now call .dequeue(), sentinel.next is null.
I asked my lecturer about this and I got the following reply, which doesn't really make it clearer for me: "When we call the constructor via Queue q = new Queue(); we will create the dummy item sentinel, whose value is zero and whose next pointer is null. At the same time we let tail point to sentinel. So clearly adding elements to the queue is not a problem."
I don't see where we let let tail point to the sentinel :/
If we now call .dequeue(), sentinel.next still points to null. This is not right. senitel only gets initialized in constructor and does not change any further.
So, After connstructor you get - (Senitel) -> null and here tail points to Senitel. You call
enqueueand it becomes. (Senitel) -> (Element1) -> null. Here, tail points to Element1 and Senitel still points to (Senitel). You call dequeue and it becomes (Senitel) - > null.