1. 题目描述
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
2. 代码实现
执行用时 :28 ms, 在所有 Python 提交中击败了63.22%的用户
内存消耗 :12.9 MB, 在所有 Python 提交中击败了10.00%的用户
# 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
"""
liNo = ListNode(-1)
l3 = liNo
while l1 and l2 :
if l1.val>=l2.val:
l3.next = l2
l3 = l3.next
l2 = l2.next
else:
l3.next = l1
l3 = l3.next
l1 = l1.next
if l1:
l3.next = l1
else:
l3.next = l2
return liNo.next
还有一种递归的方法,是我在题解中看到的,代码很简洁,有参考价值:
思路如下:
递归想法:我们可以如下递归地定义在两个链表里的 merge 操作(忽略边界情况,比如空链表等):
\left{ \begin{array}{ll} list1[0] + merge(list1[1:], list2) & list1[0] < list2[0] \ list2[0] + merge(list1, list2[1:]) & otherwise \end{array} \right.
{
list1[0]+merge(list1[1:],list2)
list2[0]+merge(list1,list2[1:])
list1[0]<list2[0]
otherwise
也就是说,两个链表头部较小的一个与剩下元素的 merge 操作结果合并。
算法:
我们直接将以上递归过程建模,首先考虑边界情况。特殊的,如果 l1 或者 l2 一开始就是 null ,那么没有任何操作需要合并,所以我们只需要返回非空链表。否则,我们要判断 l1 和 l2 哪一个的头元素更小,然后递归地决定下一个添加到结果里的值。如果两个链表都是空的,那么过程终止,所以递归过程最终一定会终止。
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2