剑指Offer第16题-合并两个排序的链表

2018-05-21  本文已影响0人  Joseph_Chu

题目

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

思路

基本思路很简单,新建一个头结点new_head,然后每次比较两个链表的头结点,把小的结点链到新头结点的后面

代码

非递归版本

# -*- 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
        p = new_head = ListNode(None)
        while True:
            if not pHead1:
                new_head.next = pHead2
                break
            if not pHead2:
                new_head.next = pHead1
                break
            if pHead1.val <= pHead2.val:
                new_head.next = pHead1
                pHead1 = pHead1.next
            else:
                new_head.next = pHead2
                pHead2 = pHead2.next
            new_head = new_head.next
        return p.next

递归版本

# -*- 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

        new_head = None
        if pHead1.val <= pHead2.val:
            new_head = pHead1
            new_head.next = self.Merge(pHead1.next, pHead2)
        else:
            new_head = pHead2
            new_head.next = self.Merge(pHead2.next, pHead1)
        return new_head
上一篇下一篇

猜你喜欢

热点阅读