【LeetCode每天一题】Merge Two Sorted Lists(合并两个排序链表)

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:        Input: 1->2->4, 1->3->4              Output: 1->1->2->3->4->4

解决思路:最简单的办法是,直接将所有元素图取出来放入内存中,然后进行排序,将排序好的结果重新构造链表然后返回。但是这样做时间复杂度较高,O((m+n)log(m+n))(m, n分别为l1 和l2 的长度), 空间复杂度为O(m+n)。

      另一种办法是,依此进行比较大小,然后将小的节点插入申请链表节点尾部,循环遍历,直到其中一个链表便遍历完毕。时间复杂度为O(m+n), 空间复杂度为O(m+n)。

    步骤图如下:

            【LeetCode每天一题】Merge Two Sorted Lists(合并两个排序链表)

 class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1 or not l2: # 其中一个空节点,直接返回非空的节点
return l1 if l1 else l2
res_node = p = ListNode() # 哨兵节点
while l1 and l2:
if l1.val < l2.val:
p.next = l1
l1 = l1.next
else:
p.next = l2
l2 = l2.next
p = p.next
p.next = l1 or l2 # 将非空的节点加到尾部
return res_node.next # 返回排序后的节点
上一篇:账号控管:NIS服务器


下一篇:NIS域配置详解