0021-leetcode算法实现之合并两个有序链表-merge-two-sorted-lists-python&golang
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
提示:
两个链表的节点数目范围是 [0, 50]
-100 <= Node.val <= 100
l1 和 l2 均按 非递减顺序 排列
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
python
# 0021.合并两个有序链表
# https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/xin-shou-you-hao-xue-hui-tao-lu-bu-fan-cuo-4nian-l/
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
def mergeTwoLists1(self, l1: ListNode, l2: ListNode) -> ListNode:
"""
递归法
:param l1:
:param l2:
:return:
"""
# 递归终止条件
if not l1: return l2
if not l2: return l1
# 选第一个节点值小的作为最后返回的链表头结点
if l1.val < l2.val:
l1.next = self.mergeTwoLists1(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists1(l1, l2.next)
return l2
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""
迭代法,虚拟头结点, 两个链表各遍历一遍,时间O(n),空间O(1)
:param headA:
:param headB:
:return:
"""
dummy = ListNode(0)
# 遍历游标
tmp = dummy
# l1 & l2 都未遍历
while l1 and l2:
# 如果l1节点值小
if l1.val < l2.val:
# l1节点作为tmp的下个节点
tmp.next = l1
# l1指向下个节点
l1 = l1.next
else:
# l2节点值小,l2作为tmp的下个节点
tmp.next = l2
# l2指向下个节点
l2 = l2.next
# 移动结果链表的结尾指针
tmp = tmp.next
# 非空节点作为最后节点
tmp.next = l1 or l2
# 返回合并链表的头结点
return dummy.next
golang
// 迭代
func mergeTwoLists1(l1, l2 *ListNode) *ListNode {
dummy := &ListNode{}
tmp := dummy
for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
tmp.Next = l1
l1 = l1.Next
} else {
tmp.Next = l2
l2 = l2.Next
}
tmp = tmp.Next
}
if l1 != nil {
tmp.Next = l1
} else {
tmp.Next = l2
}
return dummy.Next
}
// 递归
func mergeTwoLists(l1, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
if l1.Val < l2.Val {
l1.Next = mergeTwoLists(l1.Next, l2)
return l1
} else {
l2.Next = mergeTwoLists(l1, l2.Next)
return l2
}
}