【发布时间】:2017-08-06 10:34:05
【问题描述】:
问题来了。假设链表实现如下(Java):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
考虑链表:
1 -> 2 -> 3 -> 4
我会这样做:
ListNode newHead = head;
newHead = head.next.next;
//Now newHead is pointing to (3) in the linked list.
现在我施展魔法:
newHead.val = 87
链表变成:
1 -> 2 -> 87 -> 4
如果我打印了 head 和 NOT newHead。
这是为什么?我没有用 head 修改任何东西,但它仍然改变了?
【问题讨论】:
-
显然,这是因为您正在更改同一个对象。 ListNodes 仅包含对每个 ListNode 的引用。
-
@MatthiasFax,如果我上课然后这样做,总是这样吗?
-
是的,如果您不克隆或深度复制对象,则只会引用该值(除了原语)。检查这些现有问题:stackoverflow.com/questions/40480/…stackoverflow.com/questions/4600974/…
标签: algorithm data-structures linked-list