作者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://www.ptt.cc/bbs/Python/M.1538843012.A.114.html
推 jlhc: 你下id看一下new_head和pre就知道為什麼了 10/07 10:48
推 skytrek: 去了解一下python的evaluation strategy你就懂了 10/07 22:59
→ skytrek: 如果你學過C更好懂 10/07 23:00
推 handsomeLin: 第一行是dummy node 第二行是把dummy node連到head 10/08 12:02
推 handsomeLin: 我建議你寫linked list不懂就畫圖 10/08 12:15
推 mirror0227: 關鍵字 pass by reference 10/09 07:57