21. 合并两个有序链表
题目-简单难度
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例
示例 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/problems/summary-ranges
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1. 链表与列表转换求解
时间
24ms
击败 59.69%使用 Python 的用户
内存
12.96mb
击败 8.10%使用 Python 的用户
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, list1, list2):
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
# 新建列表li1
li1 = []
# 把list1链表中的值转换到li1列表中
while list1:
li1.append(list1.val)
list1 = list1.next
# 同上
li2 = []
while list2:
li2.append(list2.val)
list2 = list2.next
# 拼接列表并排序
li = sorted(li1+li2)
# 新建链表
cur = head = ListNode()
# 判断li是否为空,为空则返回空链表
if not li:
return head.next
# 遍历li列表,将值添加到新链表中
for i in range(len(li)):
# cur链表节点的值等于li列表的当前索引值
cur.val = li[i]
# 判断索引是不是最后一项
if i != len(li) - 1:
# 将cur指向下一项新建链表节点
cur.next = ListNode()
# cur移动到下一项
cur = cur.next
# 返回新链表
return head
2. 链表依次添加最小项
时间
20ms
击败 83.66%使用 Python 的用户
内存
12.72mb
击败 73.38%使用 Python 的用户
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# 判断l1链表为空,直接返回l2
if l1 == None:
return l2
# 判断l2链表为空,直接返回l1
if l2 == None:
return l1
# 新建链表
dummy = ListNode(0)
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
# 如果l1为空,将剩余的l2内容添加到链表,反之添加l1剩余部分
while l1:
cur.next = l1
cur = cur.next
l1 = l1.next
while l2:
cur.next = l2
cur = cur.next
l2 = l2.next
return dummy.next