刷题-Leetcode-21.合并两个有序链表

21.合并两个有序链表

题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/

题目描述

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

 

示例 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 均按 非递减顺序 排列

 

题目分析


迭代法

  迭代是比较容易想到的方法。

  时间复杂度 o(n) n为l1的个数加l2的个数

  空间复杂度o(n)

  

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, val=0, next=None):
 4 #         self.val = val
 5 #         self.next = next
 6 class Solution:
 7     def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
 8         #迭代法
 9         res = ListNode()
10         cur = res
11         while(l1!=None and l2!=None):
12             if l1.val<=l2.val:
13                 cur.next = l1
14                 l1 =l1.next
15                 
16             else:
17                 cur.next = l2
18                 l2=l2.next
19             cur = cur.next
20         cur.next = l1 or l2
21         return res.next
22             

 

递归法

  要有出口,此题递归终止条件为l1为空或者是l2为空。

 

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, val=0, next=None):
 4 #         self.val = val
 5 #         self.next = next
 6 class Solution:
 7     def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
 8         #递归法
 9         if l1==None or l2 == None:
10             return l1 or l2
11         
12         if l1.val<=l2.val:
13             l1.next = self.mergeTwoLists(l1.next,l2)
14             return l1
15         else :
16             l2.next = self.mergeTwoLists(l1,l2.next)
17             return l2         

 

posted @ 2021-01-10 11:45  Dul  阅读(57)  评论(0编辑  收藏  举报