You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用字典模拟链表时,无法理解字典的行为逻辑

用字典模拟链表时的指针疑惑

我尝试用Python字典模拟链表,h代表头节点,t代表尾节点:

t = {"value": 5, "next": None}
h = t

把新节点n1加到t的"next"里:

n1 = {"value": 10, "next": None}
t["next"] = n1

print(t)
# {'value': 5, 'next': {'value': 10, 'next': None}}

print(h)
# {'value': 5, 'next': {'value': 10, 'next': None}}

这时候h和t指向同一个内存地址,这点我懂,用id()也验证过。

之后我把t赋值为n1:

t = n1
print(t)
# {'value': 10, 'next': None}

print(h)
# {'value': 5, 'next': {'value': 10, 'next': None}}

这时候h和t指向不同地址,id()也验证了。

但接下来把新节点n2加到t的"next"里:

n2 = {"value": 16, "next": None}
t["next"] = n2

print(t)
# {'value': 10, 'next': {'value': 16, 'next': None}}

print(h)
# {'value': 5, 'next': {'value': 10, 'next': {'value': 16, 'next': None}}}

为什么会这样?修改t居然影响到h了?我本来以为print(h)的结果还是{'value': 5, 'next': {'value': 10, 'next': None}}。


原因解释

核心在于Python里的变量是对对象的引用,不是对象本身:

  • 当你执行t = n1时,只是让变量t指向了n1这个字典对象,但h["next"]依然指向同一个n1对象。
  • 之后执行t["next"] = n2,并不是修改变量t的指向,而是修改t所指向的那个字典对象(也就是n1)的内容——给它的"next"键赋值为n2。
  • 因为h["next"]和t此时指向的是同一个n1对象,所以这个对象的内容被修改后,通过h访问时自然能看到变化。

简单说:t和h["next"]是两个不同的变量,但它们都指向同一个字典对象,修改这个对象的内容,所有指向它的变量都会看到变化。

内容的提问来源于stack exchange,提问作者Anand Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 07:20:30