为什么此链表遍历有效?参考如何工作?

时间:2019-03-28 20:07:38

标签: java linked-list

在C语言中,使用指针可以使这个概念变得非常清晰,但是我无法理解java中到底发生了什么。

有人可以向我解释一下,当我在removeNode()中遍历列表时,为什么会发生变化,当我执行front.next = front.next.next时,它不会更改原始对象上的任何内容,而是实际上更改了对象。它使我在C中发疯,我只能使用指针来编辑想要的w / e。参考文献到底在做什么?

注意:我知道这段代码不能处理极端情况。像是空节点,等等...

public class LLnode{
    int value;
    LLnode next;

    public LLnode(int x){
        this.value = x;
        this.next = NULL;
    }
}

/*
 * This fn removes the node with the specified value n from the linked list
 */
public void removeNode(LLnode head, int n){
    LLnode front = head;
    while (front.next.value != n){
        front = front.next;  //why DOESN'T this physically change the LL?
    }
    front.next = front.next.next;  //why DOES this physically change the LL ?
}
public static void main(String[] args){
    //node creation
    LLnode a = new LLnode(10);
    LLnode b = new LLnode(20);
    LLnode c = new LLnode(30);
    LLnode d = new LLnode(40);

    //assignments
    c.next = d;
    b.next = c;
    a.next = b;

    removeNode(a,30);

}

谢谢。

1 个答案:

答案 0 :(得分:0)

Java是pass-by-valuefront = head将参考值从head复制到front。因此,front = front.nexthead没有影响。在循环front中创建它只是指向当前元素,而不用于维护列表。

但是,front.next = front.next.next更改了next引用的对象中的front字段。这里没有next字段的参考副本,就像以前的fronthead的副本一样。