2014-03-19 83 views
2

這裏是我的代碼:合併兩個排序鏈表到一個鏈表在Python

def merge_lists(head1, head2): 
    if head1 is None and head2 is None: 
     return None 
    if head1 is None: 
     return head2 
    if head2 is None: 
     return head1 
    if head1.value < head2.value: 
     temp = head1 
    else: 
     temp = head2 
    while head1 != None and head2 != None: 
     if head1.value < head2.value: 
      temp.next = head1 
      head1 = head1.next 
     else: 
      temp.next = head2 
      head2 = head2.next 
    if head1 is None: 
     temp.next = head2 
    else: 
     temp.next = head1 
    return temp 
    pass 

這裏被無限stucked loop.can任何一個問題告訴我是什麼問題

的實例是:

assert [] == merge_lists([],[]) 
assert [1,2,3] == merge_lists([1,2,3], []) 
assert [1,2,3] == merge_lists([], [1,2,3]) 
assert [1,1,2,2,3,3,4,5] == merge_lists([1,2,3], [1,2,3,4,5]) 
+2

Python本地列表成員不具有「head」和「value」屬性。你的例子不能按原樣運行。 – mtrw

+0

我沒有得到你的觀點你能否更清楚地告訴我@mtrw –

+0

@srikarthikmodukuri我們不知道'head1'和'head2'是指什麼 - 你沒有將它們包含在代碼示例中。請做。 – selllikesybok

回答

8

與當前代碼的問題是,它會導致的副作用它定位到下一個臨時節點的下一個之前來自當前節點的節點。噹噹前臨時節點是當前節點的時,這是有問題的。

也就是說,想象這種情況下:

temp = N 
temp.next = N # which means N.next = N 
N = N.next  # but from above N = (N.next = N) -> N = N 

有一個修正版本,與一些其他更新:

def merge_lists(head1, head2): 
    if head1 is None: 
     return head2 
    if head2 is None: 
     return head1 

    # create dummy node to avoid additional checks in loop 
    s = t = node() 
    while not (head1 is None or head2 is None): 
     if head1.value < head2.value: 
      # remember current low-node 
      c = head1 
      # follow ->next 
      head1 = head1.next 
     else: 
      # remember current low-node 
      c = head2 
      # follow ->next 
      head2 = head2.next 

     # only mutate the node AFTER we have followed ->next 
     t.next = c   
     # and make sure we also advance the temp 
     t = t.next 

    t.next = head1 or head2 

    # return tail of dummy node 
    return s.next 
+0

似乎很困惑。謝謝 –

2

遞歸算法合併兩個排序鏈表

def merge_lists(h1, h2): 
    if h1 is None: 
     return h2 
    if h2 is None: 
     return h1 

    if (h1.value < h2.value): 
     h1.next = merge_lists(h1.next, h2) 
     return h1 
    else: 
     h2.next = merge_lists(h2.next, h1) 
     return h2