在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);
}谢谢。
发布于 2019-03-29 04:21:33
Java是pass-by-value。front = head将参考值从head复制到front中。因此,front = front.next对head没有影响。在循环中,创建front只是为了指向当前元素,而不是用来维护列表。
但是,front.next = front.next.next会更改front引用的对象中的next字段。这里没有next字段的引用副本,就像以前front是head的副本一样。
https://stackoverflow.com/questions/55406044
复制相似问题