【问题标题】:Basic question about Linked List in PythonPython中关于链表的基本问题
【发布时间】:2020-12-05 15:17:50
【问题描述】:

让head指向以下链表的第一个元素1->2->3->Null
列表的每个元素都是具有属性的 Node():val 和 next

何时:

curr=head
head=head.next
curr.next.val= 1000
#here head.val outputs 1000 : We changed the value of the 2nd node

但是当:

curr=head
head=head.next
curr.next= Node(1000)
#here head.val outputs 2, it seems that the change
#we made in the previous line didn't
#affect the node but rather created a new 'route'.

有人能解释一下为什么在第一种情况下我们修改节点值 w.r.t head 而在第二种情况下我们没有?

谢谢

【问题讨论】:

  • 请查看有关如何格式化问题的降价指南(它不完全是 HTML)
  • 问题已编辑

标签: python linked-list


【解决方案1】:

考虑一个链表中的 3 个节点 n1、n2、n3。

head = n1
curr = head
# All n1, head and curr will be pointing to same memory.
head = head.next
# head will be reasigned to n2, but curr points to n1 itself.
第一种情况
curr.next.val = 1000
# curr.next is same as n1.next which is n2 so n2.val becomes 1000
# As head points to n2 head.val is also 1000
第二种情况
curr.next = node(1000)
# it reassigns curr.next i.e n1.next to new node with val = 1000 (head is unaltered)
# Here as head points to n2, head.val = 2

这里重要的是 head = head.next 仅重新分配 head 而不是 curr

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多