21. 合併兩個有序鍊錶
將兩個公升序鍊錶合併為乙個新的 公升序 鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。
示例 1:
輸入:l1 = [1,2,4], l2 = [1,3,4]
輸出:[1,1,2,3,4,4]
示例 2:
輸入:l1 = , l2 =
輸出:示例 3:
輸入:l1 = , l2 = [0]
輸出:[0]
解析:如果 l1 或者 l2 一開始就是空鍊錶 ,那麼沒有任何操作需要合併,所以我們只需要返回非空鍊錶。否則,我們要判斷 l1 和 l2 哪乙個鍊錶的頭節點的值更小,然後遞迴地決定下乙個新增到結果裡的節點。如果兩個鍊錶有乙個為空,遞迴結束。
# definition for singly-linked list.
# class listnode:
# def __init__(self, val=0, next=none):
# self.val = val
# self.next = next
class
solution
:def
mergetwolists
(self, l1: listnode, l2: listnode)
-> listnode:
ifnot l1:
return l2 # 終止條件,直到兩個鍊錶都空
ifnot l2:
return l1
if l1.val <= l2.val:
# 遞迴呼叫
l1.next
= self.mergetwolists(l1.
next
,l2)
return l1
else
: l2.
next
= self.mergetwolists(l1,l2.
next
)return l2
leetcode刷題之旅 21 合併兩個有序鍊錶
definition for singly linked list.struct listnode listnode int x val x next nullptr listnode int x,listnode next val x next next class solution cur ne...
LeetCode刷題日記 21 合併兩個有序鍊錶
今天是開始刷leetcode的第一天,看到題目還幾乎沒有思路。準備先從鍊錶題開始刷。先看答案,然後根據答案掌握c 鍊錶相關用法。根據課程,寫下以下暴力解 definition for singly linked list.struct listnode listnode int x val x ne...
leetcode刷題之路21 合併兩個有序鍊錶
將兩個有序鍊錶合併為乙個新的有序鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。示例 輸入 1 2 4,1 3 4 輸出 1 1 2 3 4 4 思路 始終讓l1是頭節點小的那乙個,然後拿l2的節點值依次與l1比較並插入l1中。最後返回l1。include using namespace...