题目21:合并两个有序链表
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
知识点补充&回顾(链表)
- python数据结构之链表(一) - King_DIG - 博客园 https://www.cnblogs.com/king-ding/p/pythonchaintable.html
- python:链表定义以及实现 - DinnerHowe的博客 - 优快云博客 https://blog.youkuaiyun.com/dinnerhowe/article/details/58191823
- 链表的Python实现与实例分析 - 不知道起什么名字 - 优快云博客 https://blog.youkuaiyun.com/songyunli1111/article/details/79357632
- Python数据结构之单链表详解_python_脚本之家 https://www.jb51.net/article/123464.htm
- 用 python 学习数据结构(一)链表 - 简书 https://www.jianshu.com/p/73dd103614ab
代码实现
迭代方法
每次选两个链表头结点最小的,比如:我们生活中,有两个已经按照高矮排好的队伍,我们如何把变成一个队伍!当然,每次选两个队伍排头的,比较他们的高矮!组成新的的队伍。
时间复杂度:O(m+n)
空间复杂度:O(m+n)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
p = dummy
while l1 or l2:
if l1 and l2:
tmp1 = l1.val
tmp2 = l2.val
if tmp1 < tmp2:
p.next = ListNode(tmp1)
l1 = l1.next
else:
p.next = ListNode(tmp2)
l2 = l2.next
elif l1:
p.next = ListNode(l1.val)
l1 = l1.next
elif l2:
p.next = ListNode(l2.val)
l2 = l2.next
p = p.next
return dummy.next
递归方法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1: return l2
if not 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
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 and l2:
if l1.val > l2.val:
l1, l2 = l2, l1
l1.next = self.mergeTwoLists(l1.next, l2)
return l1 or l2