# leetcode-21：合并两个有序链表

## 题目

输入：l1 = [1,2,4], l2 = [1,3,4]

输入：l1 = [], l2 = []

输入：l1 = [], l2 = [0]

## 解题

### 方法一：递归

# 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, l2):
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(l1, l2.next)
return 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:
dummy = ListNode()
cur = dummy
while l1 and l2:
if l1.val<=l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 if l1 is not None else l2
return dummy.next

# 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:
dummy = curr = ListNode()
while l1 or l2:
if not l1:
curr.next = l2
break
if not l2:
curr.next = l1
break
if l1.val<l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
return dummy.next

|
11天前
|

LeetCode力扣第114题：多种算法实现 将二叉树展开为链表
LeetCode力扣第114题：多种算法实现 将二叉树展开为链表
10 0
|
4天前
|

[Java·算法·中等] LeetCode21. 合并两个有序链表
[Java·算法·中等] LeetCode21. 合并两个有序链表
12 2
|
7天前
|
Java Python

10 1
|
7天前
21. 合并两个有序链表
21. 合并两个有序链表
8 1
|
11天前
|

LeetCode 题目 86：分隔链表
LeetCode 题目 86：分隔链表
15 2
|
11天前
|

11 1
|
11天前
|
SQL 算法 数据可视化
LeetCode题目92:反转链表ll 【python 递归与迭代方法全解析】
LeetCode题目92:反转链表ll 【python 递归与迭代方法全解析】
9 1
|
8天前
|

【经典LeetCode算法题目专栏分类】【第7期】快慢指针与链表
【经典LeetCode算法题目专栏分类】【第7期】快慢指针与链表
7 0
|
11天前
|

LeetCode 83题：删除排序链表中的重复元素【面试】
LeetCode 83题：删除排序链表中的重复元素【面试】
5 0
|
11天前
|

LeetCode 题目 82：删除排序链表中的重复元素 II
LeetCode 题目 82：删除排序链表中的重复元素 II
9 0