Old Wei wins the offer to take you to learn --- Brush title series (16 merge two sorted lists)

16. merge two sorted lists

problem:

Two monotonically increasing input list and output list after synthesis of two lists, of course, after that we need to meet synthesis list - decreasing the rules.

solve:

thought:

  • This question can use the recursive implementation, the new list does not need to construct new nodes, we recursively three elements listed below
  • Termination condition: two are named list l1 and l2, when the end l2 l1 is empty or empty
  • Returns: Each layer calls return the sorted list head
  • This recursion level content: if the value of the val l1 is smaller, then l1.next contact with the sorted list head, l2 empathy
  • O (m + n) O (m + n), mm of length l1, nn is the length l2

python code

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回合并后列表
    def Merge(self, pHead1, pHead2):
        # write code here
        if(pHead1==None):
            return pHead2
        if(pHead2==None):
            return pHead1
        if(pHead1.val<pHead2.val):
            pHead1.next=self.Merge(pHead1.next,pHead2)
            return pHead1
        else:
            pHead2.next=self.Merge(pHead1,pHead2.next)
            return pHead2
Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/104905827