Monday, 11 September 2017

algorithm - Java Queue Implementation with Pointers

I need help understanding this. I know how to implement the queue but there is one small part bothering me. I drew on my notebook the flow of how things work but I don't get how the head has a nextNode without me setting it. How does the head end up pointing to the next node?



public void enqueue(T data){
count++;
Node current = tail;
tail = new Node<>(data);
if(isEmpty()) {

///////////////////////////////////////////////////////////////////////////////
// when this runs, doesn't head.getNextNode point to null?
// if the list is empty, then tail is null.
// On the deque method, I can sout head.getNextNode() and I get data back, how?
///////////////////////////////////////////////////////////////////////////////
head = tail;

} else {
current.setNextNode(tail);
}

}


Below, the dequeing works fine, I think I'm having an issue understanding the whole reference/pointer thing



public T dequeue() {
if(isEmpty()) {
return null;
}
count--;

T dataToRemove = head.getData();
/////////////////////-+{[UPDATE]}+-////////////////////////////////
// WHERE DOES HEAD GET THE NEXT NODE FROM? THIS WORKS, BUT WHERE IS
// THE NEXT NODE COMING FROM IS WHAT I'M ASKING?
///////////////////////////////////////////////////////////////////
head = head.getNextNode();

return dataToRemove;
}

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...