【题目描述】
【代码思路】 最终返回的是一个新的链表的头结点,因此先定义一个新的空结点作为返回结果的头部,因为这个头结点内容为None,我们最终返回的是head.next这个结点,再定义一个current结点,用于在循环中指向新链表的尾部,以便找到l1,l2中较小的,链接在尾部之后。head=ListNode(None)
current=head
复制代码
在一个循环中,当l1和l2都不为空时,从两个链表的头结点开始做比较,在每次循环中,找到l1,l2中较小的那个结点,假如l1.val较小,链接在current之后,即current.next=l1,然后l1和current都依次向后错一位,current到新链表的尾部,l1到下一个比较位置。
current.next=l1
current=l1
l1=l1.next
复制代码
直至l1,l2中有一者或者二者都为空的时候,while循环结束,把二者中不为空的那个结点链接在current之后即可。
if l1:current.next=l1
if l2:current.next=l2
复制代码
这个解决办法的空间复杂度为O(1)因为只多占用了head和current两个结点空间。时间复杂度为O(m+n),m,n是两个输入链表的长度,因为只遍历了两个链表一次。 【源代码】
# 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
"""
head=ListNode(None)
current=head
while l1 and l2:
if l1.val<=l2.val:
current.next=l1
current=l1
l1=l1.next
else:
current.next=l2
current=l2
l2=l2.next
if l1:current.next=l1
if l2:current.next=l2
return head.next
复制代码