I am looking at the implementation of Queue from Cracking the Code Interview 5th Edition.
The explanation of enqueue is as follows:
class Queue {
Node first, last;
void enqueue(Object item) {
// This indicates the Queue is empty
// so we set both first and last as
// the same item
if(first == null) {
last = new Node(item);
first = last;
} else {
last.next = new Node(item);
last = last.next;
}
}
}
I understand what is going on in the if-statement. This conditional deals with an empty queue. So if the queue is empty, and we're trying to add an item to the queue, the item added is both the first and last item.
However, what I am not understanding is what's going on in the else statement. The book first assigns the item as the last.next
, and then assigns last
as last.next
. Wouldn't this make both the last and last's next element the same thing? Also, I illustrated the queue. Is this an accurate illustration of the positions of last
and last.next
?
[ | | | ]
^ ^
last last.next
The code in the else section:
1: last.next = new Node(item);
2: last = last.next;
Here's the LL we start with:
(a) -> (b) -> (c)
^first ^last
We call enqueue(d)
After line 1 runs:
(a) -> (b) -> (c) -> (d)
^first ^last
So we see that line 1 creates a new element at the end of the list, but last
still points to (c)
.
After line 2 runs:
(a) -> (b) -> (c) -> (d)
^first ^last
Now, last
points at (d)
which appropriately has no next
node.
You see, (c)
never goes away, it is simply the last
reference that is moved .
As for why this is how it works, it all comes down to the fact that objects are references in Java.
Consider this code:
Object x = 300;
Object y = 500;
Object z = x;
//here, x = 300, y = 500, z = 300
x = y;
//now, x = 500, y = 500, z = 300
//because the actual object that x initially pointed to was not changed, only x as a reference was changed.
In the case where the list has size n=0
, and n=1
respectively:
NULL
^first,last
NULL (a)
^first ^last
(a)
^first,last
Then another call
(a)
^first,last
(a) -> (b)
^first,last
(a) -> (b)
^first ^last
Hope that helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.