演算法 合併兩個有序鍊錶

2022-07-11 05:36:10 字數 1396 閱讀 9089

1. 迭代,

新建乙個哨兵節點,通過它的next指標指向串聯起兩個鍊錶

比較 l1 和 l2哪乙個比較小,讓哨兵節點的next指向比較小的節點

哨兵節點 l1 l2依次後推,直到又乙個鍊錶為空

如果 l1 為空,則哨兵節點指向l2

注意返回值為哨兵節點的next,因為哨兵節點的第乙個值是隨意給的

class listnode(object):

def __init__(self, val

=0, next

=none):

self.val

=val

self.

next

=next

class solution(object):

def mergetwolists(self, l1, l2):

""":type l1: listnode

:type l2: listnode

:rtype: listnode

"""prev

= listnode(-1)

p =prev

while l1 and

l2:

if l1.val <=

l2: p.

next=l1

l1 = l1.next

else

: p.

next=l2

l2 = l2.next

p = p.next

if l1 is

notnone:

p.next=l1

else

: p.

next=l2

return prev.next

2. 遞迴的方式————————推薦!!!

找到 l1 和 l2 的較小的節點

從後往前依次追加節點

注意next的運用

if l1 is

none:

return

l2 elif l2

isnone:

return

l1 elif l1.val

<

l2.val:

l1.next

= self.mergetwolists(l1.next

, l2)

return

l1

else

: l2.

next

= self.mergetwolists(l1, l2.next

)

return l2

不額外花費空間儲存

演算法 合併兩個有序鍊錶

有兩種方法,迭代和遞迴。迭代 不帶頭結點 node merge node head1 node head2 else 當前排序好的鍊錶的末尾節點 node pcurrent head while p1 null p2 null else 還有一方沒有遍歷完的情況 if p1 null pcurren...

合併兩個有序鍊錶

鍊錶的題目總是讓我很惆悵。動輒就會runtime error。比如這題,額外用了乙個節點的空間來儲存頭節點。我很不情願多用這個空間,不過貌似不行。貌似不行,實際可行,見附錄。把頭節點提出迴圈 實現類 class solution else if l1 null p next l1 if l2 nul...

合併兩個有序鍊錶

三個指標乙個儲存la鍊錶 乙個儲存lb鍊錶,乙個指向新的鍊錶。鍊錶的插入,兩個指標,乙個是head,乙個指向head後面的鏈,新插入的元素位於head後面。執行該 自己外加上class類。static class node public static void main string args st...