leedcode合併兩個有序鍊錶

2021-09-27 03:59:26 字數 1191 閱讀 3356

構建乙個新鍊錶,遍歷這兩個有序鍊錶,將較小值加入到新鍊錶。直到兩個有序鍊錶至少有乙個遍歷結束為止。

對於沒有遍歷完的有序鍊錶,將其剩餘的元素加入到新鍊錶的後面、

# definition for singly-linked list.

#class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

def mergetwolists(self, l1: listnode, l2: listnode) -> listnode:

l_new = listnode(none)

ll_new = l_new

if l1 == none and l2 == none:

return

while (l1 != none) and (l2 != none):

if l1.val <= l2.val:

l_new.val = l1.val

l1 = l1.next

l_new.next = listnode(none)

l_new = l_new.next

else:

l_new.val = l2.val

l2 = l2.next

l_new.next = listnode(none)

l_new = l_new.next

while l1 != none:

l_new.val = l1.val

l1 = l1.next

l_new.next = listnode(none)

l_new = l_new.next

while l2 != none:

l_new.val = l2.val

l2 = l2.next

l_new.next = listnode(none)

l_new = l_new.next

l2_new = ll_new

while ll_new.next.val != none:

ll_new = ll_new.next

ll_new.next = none

return l2_new

Leedcode 每日一題 合併兩個有序鍊錶

將兩個有序鍊錶合併為乙個新的有序鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。示例 輸入 1 2 4,1 3 4 輸出 1 1 2 3 4 4 迭代法 definition for singly linked list.struct listnode class solution el...

合併兩個有序鍊錶

鍊錶的題目總是讓我很惆悵。動輒就會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...