LeetCode 21 合併兩個有序鍊錶

2021-08-31 16:23:01 字數 1722 閱讀 4399

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

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

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

看到題目,首先想到直接把兩個鍊錶合成乙個鍊錶,後來發現直接使用鍊錶太麻煩了,不太會寫然後打算把初始兩個鍊錶轉換為列表合併,**如下:

# definition for singly-linked list.

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

def mergetwolists(self, l1, l2):

""":type l1: listnode

:type l2: listnode

:rtype: listnode

"""list1=

list2=

s=if l1==none and l2==none:

return none

elif l1==none and l2:

return l2

elif l2==none and l1:

return l1

else:

while l1.next!=none:

l1=l1.next

while l2.next!=none:

l2=l2.next

#將兩個鍊錶轉換為列表便於操作

while list1!= and list2!=:

if list1[0]<=list2[0]:

a=list1.pop(0)

else:

b=list2.pop(0)

if list1==:

s=s+list2

if list2==:

s=s+list1

return s

注意有時候輸入由空鍊錶的情況

後來在網上查了一下大佬的**,使用了遞迴的方法,**簡潔易懂。

# definition for singly-linked list.

# class listnode:

# def __init__(self, x):

# self.val = x

# self.next = none

class solution:

def mergetwolists(self, l1, l2):

""":type l1: listnode

:type l2: listnode

:rtype: listnode

"""if l1==none and l2==none:

return none

if l1==none:

return l2

if l2==none:

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合併兩個有序列表

將兩個公升序鍊錶合併為乙個新的公升序鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。輸入 1 2 4,1 3 4 輸出 1 1 2 3 4 4初始解法 這個問題轉換為經典的merge排序中的merge過程.merge排序中merge操作即是將兩個有序子陣列合併成乙個陣列,需要考慮比較過程...

leetcode21 合併兩個有序鍊錶

將兩個有序鍊錶合併為乙個新的有序鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。示例 輸入 1 2 4,1 3 4 輸出 1 1 2 3 4 4 思路 每次判斷兩個鍊錶的頭部小的數值,訪問小的,並讓該鍊錶往後移動。注意 注意鍊錶走完,為空的情況即可。遇到的問題 一開始不太理解鍊錶,返回e...

LEETCODE 21 合併兩個有序鍊錶

將兩個有序鍊錶合併為乙個新的有序鍊錶並返回。新煉表是通過拼接給定的兩個鍊錶的所有節點組成的。示例 輸入 1 2 4,1 3 4 輸出 1 1 2 3 4 4c 第一遍將 相等 的這個else分支寫錯了,主要錯誤在於,next指標指向下乙個的這條語句寫到了後面,導致節點自己指向自己,造成了超時錯誤 執...