首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么这种链表遍历会起作用?引用是如何工作的?

为什么这种链表遍历会起作用?引用是如何工作的?
EN

Stack Overflow用户
提问于 2019-03-29 04:07:38
回答 1查看 42关注 0票数 0

在C语言中,这个概念通过指针变得非常清晰,但是我很难理解java到底是怎么回事。

有人能给我解释一下,为什么当我在removeNode()中遍历列表时,它没有改变原始对象上的任何东西,但当我执行front.next = front.next.next时,它实际上改变了对象。这让我抓狂,因为在C中,我可以使用指针来编辑我想要的w/e。这些引用到底是怎么回事?

注意:我知道这段代码不能处理边缘情况。例如空节点,等等。

代码语言:javascript
复制
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);

}

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-29 04:21:33

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55406044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档