[問題] 新手解LeetCode:Swap Nodes in Pairs

作者: iwantstronge (...)   2016-08-03 02:58:25
最近開始用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 <
作者: Sunal (SSSSSSSSSSSSSSSSSSSSSSS)   2016-08-03 11:59:00
你的第二個問題印出id(pre)跟id(dummy)就可以知道了
作者: Yshuan (倚絃)   2016-08-03 14:24:00
你的推測是對的 通常是因為mutable 這case是小整數的優化
作者: s06yji3 (阿南)   2016-08-03 19:22:00
你那兩個對調,在while後的第3行就變成無限迴圈了物件的=是設定reference看錯,是第二行就變無限迴圈了(對調的第一行)

Links booklink

Contact Us: admin [ a t ] ucptt.com