NOWCODER 剑指offer 合并两个排序的链表

运行时间:21ms

占用内存:5724k

链表我经常进入死循环而且不知道哪里出错。。要细致

非递归算法O(min(m,n))

# -*- 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 (not pHead1):
            return pHead2
        if (not pHead2):
            return pHead1
        head3 = None
        while(pHead1 and pHead2):
            if (pHead1.val>=pHead2.val):
                if(not head3):
                    head3 = pHead2
                    current = head3
                else:
                    current.next = pHead2
                    current = current.next
                pHead2 = pHead2.next
            else:
                if(not head3):
                    head3 = pHead1
                    current = head3
                else:
                    current.next = pHead1
                    current = current.next
                pHead1 = pHead1.next
        if(pHead1):
            current.next = pHead1
        else:
            current.next = pHead2
        return head3

————————————————————————————————————

递归算法O(n)

运行时间:29ms

占用内存:5728k

# -*- 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 (not pHead1):
            return pHead2
        if (not pHead2):
            return pHead1
        if (pHead1.val>=pHead2.val):
            head3 = pHead2
            head3.next = self.Merge(pHead1,pHead2.next)
        else:
            head3 = pHead1
            head3.next = self.Merge(pHead1.next,pHead2)
        return head3

猜你喜欢

转载自blog.csdn.net/u014381464/article/details/81952662
今日推荐