[問題] leetcode 203 linked list移除element

看板Python作者 (jeff)時間5年前 (2018/10/07 00:23), 編輯推噓5(501)
留言6則, 4人參與, 5年前最新討論串1/1
大家好 我有個關於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

10/07 10:48, 5年前 , 1F
你下id看一下new_head和pre就知道為什麼了
10/07 10:48, 1F

10/07 22:59, 5年前 , 2F
去了解一下python的evaluation strategy你就懂了
10/07 22:59, 2F

10/07 23:00, 5年前 , 3F
如果你學過C更好懂
10/07 23:00, 3F

10/08 12:02, 5年前 , 4F
第一行是dummy node 第二行是把dummy node連到head
10/08 12:02, 4F

10/08 12:15, 5年前 , 5F
我建議你寫linked list不懂就畫圖
10/08 12:15, 5F

10/09 07:57, 5年前 , 6F
關鍵字 pass by reference
10/09 07:57, 6F
文章代碼(AID): #1RkE644K (Python)