题目在leetcode上的链接为:
https://leetcode-cn.com/problems/merge-two-sorted-lists/
题目描述
解题思路
使用归并排序的合并有序数组的思路即可。
复杂度分析:
需要遍历两个链表,时间复杂度为 o(m+n)
只需要创建常数个指针变量,空间复杂度为 o(1)
python代码
# 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 l1 is None:
return l2
if l2 is None:
return l1
newhead = p = ListNode(-1)
while l1 is not None and l2 is not None:
if l1.val <= l2.val:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
p.next = l1 if l1 is not None else l2
return newhead.next