checking reference to a node object
i have a q开发者_如何学Gouestion about this code.
class Queue {
Node first, last
void enqueue(Object item){
if(!first){
last = new Node(item);
first = last;
} else {
last.next = new Node(item);
last = last.next;
}
}
}
i guess im not really sure what exactly Node last is. When i write the line Node first, last, i heard i am making a reference to a node object. What exactly does that mean? Is it pointing to anywhere in memory? I know I never call the constructor so its not a new object. Could you give me some insight?
And what exactly does if(!first) mean? What is the if statement checking for since first is not a boolean? Thanks!
I would much appreciate clear and simple help. Thanks = )
The Node first, last
line is declaring two variables of type Node. One of them is named first, the second is named last. These node objects are reference objects, because they contain the address to the data in memory, rather than containing the data itself.
More on reference vs value types: http://cplus.about.com/od/learnc/ss/value.htm
The line last = new Node(item);
is actually calling the Node's constructor. A new node is created, and it contains the item that was passed in.
if(!first)
checks to see if the first node is empty. If it is empty, then that code block is executed. Otherwise the second block is executed.
精彩评论