leetcode合併兩個有序列表

2021-10-03 15:17:51 字數 1233 閱讀 7491

將兩個有序鍊錶合併為乙個新的有序鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。

例如:輸入:1->2->4, 1->3->4

輸出:1->1->2->3->4->4

class

solution

:def

mergetwolists

(self, l1: listnode, l2: listnode)

-> listnode:

head = listnode(

none

)

c=head

while l1 and l2:

if l1.val < l2.val:

c.next

= l1

l1 = l1.

next

else

:

c.next

= l2

l2 = l2.

next

c = c.

next

c.next

= l1 if l1 else l2

return head.

next

class

solution

:def

mergetwolists

(self, l1: listnode, l2: listnode)

-> listnode:

#參考官方題解,用遞迴,bulijie

if l1 is

none

:return l2

elif l2 is

none

:return l1

elif l1.val < l2.val:

l1.next

= self.mergetwolists(l1.

next

, l2)

return l1

else

: l2.

next

= self.mergetwolists(l2.

next

, l1)

return l2

這個演算法採用遞迴的思路,使**簡潔了很多。

合併兩個有序列表

1.尾遞迴 1 def recursion merge sort2 l1,l2,tmp 2if len l1 0 or len l2 0 3tmp.extend l1 4tmp.extend l2 5return tmp6 else 7 if l1 0 dell1 0 10else 11 12del...

Go實現合併兩個有序列表(leetcode 21)

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

LeetCode 簡單 合併兩個有序列表 c

題目為將兩個有序鍊錶合併為乙個新的有序鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。示例 輸入 1 2 4,1 3 4 輸出 1 1 2 3 4 4 其中存在乙個類,結構為 public class listnode 每乙個都會指向下乙個元素。編寫的c 如下 public static...