题目
输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。
样例
输入:1->3->5 , 2->4->5
输出:1->2->3->4->5->5
思路
v1:二路归并(推荐)
【1】新建头部的保护结点dummy,设置cur指针指向dummy。
【2】若当前L1指针指向的结点的值L1.val比L2指针指向的结点的值L2.val小,则令cur的next指针指向L1,且L1后移;否则指向L2,且L2后移。然后cur指针后移。
【3】循环以上步骤直到L1或L2为空。将剩余的L1或L2接到cur指针后边。
时间复杂度:两个链表各遍历一次,所以时间复杂度为O(n)
v2:递归
代码v1
class Solution(object):
def merge(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(-1)
cur = dummy
while l1 and l2:
if l1.val<=l2.val:
cur.next = l1
l1 = l1.next
elif l2.val < l1.val:
cur.next = l2
l2 = l2.next
cur = cur.next
if l1:
cur.next=l1
elif l2:
cur.next=l2
return dummy.next
# 推荐用if,直接把较长链表的剩余部分一次性加到cur后面
# 用while 则稍微冗长一些
while l1:
cur.next = l1
l1 = l1.next
cur = cur.next
while l2:
cur.next = l2
l2 = l2.next
cur = cur.next
return dummy.next
代码v2
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def merge(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
l1.next = self.merge(l1.next, l2)
return l1
else:
l2.next = self.merge(l1, l2.next)
return l2