如何解决从重复项中删除链表 - leetcode - 代码问题 - python
我正在学习链表,找到了这个解决方案,但对一个简单的编码问题感到非常困惑。目标是删除排序链表中的重复项。 输入:[4,4,5,6] 输出:[4,6]
我的代码:
class ListNode:
def __init__(self,val=0,next=None):
self.val = val
self.next = next
def deldup(head):
cn = head
while cn is not None:
nn = cn.next
while nn is not None and nn.val == cn.val:
nn = nn.next
cn.next = nn
cn = nn
return head
测试代码:
a = ListNode(4)
a.next = ListNode(5)
a.next.next = ListNode(5)
a.next.next.next = ListNode(6)
def printll(ll):
tmp = ll
while tmp:
print(tmp.val)
tmp = tmp.next
b = deldup(a)
printll(b)
-->4,6
我的问题是在 deldup 函数中,它返回输入变量 head,但在整个过程中,cn = head,当我们只是更新 cn 而不是 head 时,如何在 while 循环期间更新 head?换句话说,我不明白函数中的 head 怎么会得到更新?
def f(a):
cn = a
i = 0
while i < 5:
cn = i
i += 1
return a
b = f(10)
print(b)
--> 10
在这个例子中,简单地改变cn的值不会影响a的值,但是在deldup函数中,改变cn的值怎么会影响输入变量“head”的值呢?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。