在单链表中更新尾节点的 nextRef 时如何更新头节点的 nextRef

How head node's nextRef got updated while updating tail node's nextRef in Single Linked List

我试图根据参考文献 link http://www.java2novice.com/data-structures-in-java/linked-list/singly-linked-list/.

理解 LinkedList 实现

他们在那里创建了一个节点 class,如下所示:

class Node<T> implements Comparable<T> {

    private T value;
    private Node<T> nextRef;

    public T getValue() {
        return value;
    }
    public void setValue(T value) {
        this.value = value;
    }
    public Node<T> getNextRef() {
        return nextRef;
    }
    public void setNextRef(Node<T> ref) {
        this.nextRef = ref;
    }
    @Override
    public int compareTo(T arg) {
        if(arg == this.value){
            return 0;
        } else {
            return 1;
        }
    }
}

并实现单向链表如下:

    public class SinglyLinkedListImpl<T> {

    private Node<T> head;
    private Node<T> tail;

    public void add(T element){

        Node<T> nd = new Node<T>();
        nd.setValue(element);
        System.out.println("Adding: "+element);
        /**
         * check if the list is empty
         */
        if(head == null){
            //since there is only one element, both head and 
            //tail points to the same object.
            head = nd;
            tail = nd;
        } else {
            //set current tail next link to new node
            //When this line gets executed, it's also updating head variable's nextRef object. How that works?!?!
            tail.setNextRef(nd);
            //set tail as newly created node
            tail = nd;
        }
    }
    ...
    ...
}

我无法理解下一行何时被执行,它也在更新 head 变量的 nextRef 对象。这是怎么回事?!?!

tail.setNextRef(nd);

我已经尝试调试并查看对象的值,并注意到只有在 head 变量中它们才不断添加给定的元素 nextRef。但是 head.nextRef 如何在 tail.setNextRef(nd) 步更新!!!

这可能是一个愚蠢的问题,但对它的发生感到疯狂! :(

添加第一个元素时,head 和 tail 都指向同一个元素。添加第二个元素时,tail.setNextRef(nd) 将等于 head.setNextRef(nd),因为 tail 和 head 具有相同的引用。之后tail=nd,表示tail现在指向当前节点,从那一点开始,当前节点的next会通过tail.setNextRef(nd)设置,紧接着tail就会有新的当前节点参考。

我希望这能说明问题。