题目描述
leetcode题目链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
题目分析
-
方法一:递归
我们递归定义两个链表里的merge
操作,先不考虑边界:
{ l i s t 1 [ 0 ] + m e r g e ( l i s t 1 [ 1 ] , l i s t 2 [ 0 ] ) l i s t 1 [ 0 ] < l i s t 2 [ 0 ] l i s t 2 [ 0 ] + m e r g e ( l i s t 1 [ 0 ] , l i s t 2 [ 1 ] ) o t h e r v i s e \left\{ \begin{aligned} &list1[0] + merge(list1[1], list2[0]) & list1[0]<list2[0]\\ &list2[0] + merge(list1[0], list2[1]) & othervise \end{aligned} \right. {list1[0]+merge(list1[1],list2[0])list2[0]+merge(list1[0],list2[1])list1[0]<list2[0]othervise
也就是说,两个链表头部值较小的一个节点与剩下元素的 merge 操作结果合并。
考虑边界:若l1,或者l2其中一方为空,返回另一方。若开始皆为空,那返回另一方也为空,也满足条件。 -
方法二:迭代
迭代初始:建立头指针FNode
,和一个前向指针pre
初始指向FNode
。
迭代开始:将pre.next
指向两链表中值小的节点上,pre
前移。
迭代结束:定有一方链表指针为None
,将pre.next
指向将另一方当前节点上。返回FNode.next
特殊情况:一开始两链表均为None
,返回值也是None
,满足条件。
代码
/*
方法1: 递归
*/
# 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(l2.next, l1)
return l2
/*
方法二:迭代
*/
# 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:
FNode = ListNode(-1)
pre = FNode
while l1 and l2:
if l1.val < l2.val:
pre.next = l1
l1 = l1.next
else:
pre.next = l2
l2 = l2.next
pre = pre.next
pre.next = l1 if l1 else l2
return FNode.next