- #1
n00neimp0rtnt
- 15
- 0
I just took my final for Data Structures and there was a question on it dealing with linked lists. A part of the question really threw me off. It looked something like this:
The part of concern is in bold. When I read this, it looks like in the first line, tail.next is getting set to the Node that the reference "newNode" is pointing to. In the SECOND line, however, tail is getting set to the Node that "newNode" points to. If I'm not mistaken, doesn't that just nullify the first statement as if it was never executed? What happens to tail.next? After the second statement, isn't tail.next pointing to the same Node that newNode.next points to? I thought it was a typo so I asked my professor and he simply said that "tail.next is not 'inside' tail; they are two separate things," which didn't really help much.
Code:
public class Node
{
int contents;
Node next;
}
public class LinkedList
{
Node head, tail;
}
public void bar(int c)
{
newNode = new Node();
newNode.contents = c;
[B]tail.next = newNode;
tail = newNode;
newNode.next = null;[/B]
}
The part of concern is in bold. When I read this, it looks like in the first line, tail.next is getting set to the Node that the reference "newNode" is pointing to. In the SECOND line, however, tail is getting set to the Node that "newNode" points to. If I'm not mistaken, doesn't that just nullify the first statement as if it was never executed? What happens to tail.next? After the second statement, isn't tail.next pointing to the same Node that newNode.next points to? I thought it was a typo so I asked my professor and he simply said that "tail.next is not 'inside' tail; they are two separate things," which didn't really help much.