作者typhoonss821 (jeff)
看板Python
标题[问题] leetcode 203 linked list移除element
时间Sun Oct 7 00:23:29 2018
大家好
我有个关於linked list的问题
题目是:
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
-----------------------------
我在Google上找到这题的解法(原谅我初学还需要观摩其他人的答案..)
https://blog.csdn.net/coder_orz/article/details/51706294
附上程式码:
def removeElements(self, head, val):
new_head = pre = ListNode(0)
pre.next = head
while head:
if head.val == val:
pre.next = head.next
else:
pre = pre.next
head = head.next
return new_head.next
我不理解的地方是他update pre之後为什麽new_head也会随之被update?
每次pre = pre.next後pre的长度越来越小,为什麽new_head.next还能给出正确答案呢?
先谢谢大家的解答了!
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 173.68.93.212
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1538843012.A.114.html
1F:推 jlhc: 你下id看一下new_head和pre就知道为什麽了 10/07 10:48
2F:推 skytrek: 去了解一下python的evaluation strategy你就懂了 10/07 22:59
3F:→ skytrek: 如果你学过C更好懂 10/07 23:00
4F:推 handsomeLin: 第一行是dummy node 第二行是把dummy node连到head 10/08 12:02
5F:推 handsomeLin: 我建议你写linked list不懂就画图 10/08 12:15
6F:推 mirror0227: 关键字 pass by reference 10/09 07:57