作者iwantstronge (...)
看板Python
標題[問題] 新手解LeetCode:Swap Nodes in Pairs
時間Wed Aug 3 02:58:25 2016
最近開始用Python解題
未學過正規的Python 因此對於一些觀念尚不太了解
題目是將鏈表中的元素兩兩對調
例如: Given 1->2->3->4, return the list as 2->1->4->3
我的Code如下:
class Solution(object):
def swapPairs(self, head):
if head is None or head.next is None:
return head
dummy = ListNode(0)
dummy.next = head
pre = dummy
tmp = head
while tmp and tmp.next:
pre.next = tmp.next
tmp.next = tmp.next.next <---有疑問
pre.next.next = tmp <---有疑問
pre = tmp
tmp = tmp.next
return dummy.next
以上的Code沒問題
但如果我將上面標示有疑問的那兩行順序對調,改成:
class Solution(object):
def swapPairs(self, head):
if head is None or head.next is None:
return head
dummy = ListNode(0)
dummy.next = head
pre = dummy
tmp = head
while tmp and tmp.next:
pre.next = tmp.next
pre.next.next = tmp <---已對調
tmp.next = tmp.next.next <---已對調
pre = tmp
tmp = tmp.next
return dummy.next
系統將會出現Time Limit的錯誤
就我的認知,這兩行對調應該完全沒差別?
另一個問題是,我在一開始將dummy指定給pre 掃描鏈表時是用pre在跑
而最後直接return dummy時,dummy也會跟著pre的變化而改變? 代表那個'等號'的operator
是有傳址的意味在,而不像一般的等號直接複製到另一塊新的記憶體?
以上問題,還請高手們提點,感激不盡!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.31.161.60
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1470164308.A.F45.html
推 Sunal: 你的第二個問題印出id(pre)跟id(dummy)就可以知道了 08/03 11:59
推 Yshuan: 你的推測是對的 通常是因為mutable 這case是小整數的優化 08/03 14:24
推 s06yji3: 你那兩個對調,在while後的第3行就變成無限迴圈了 08/03 19:22
推 s06yji3: 物件的=是設定reference 08/03 19:24
推 s06yji3: 看錯,是第二行就變無限迴圈了(對調的第一行) 08/03 19:32