剑指Offer-Python-牛客网

面试题25:合并两个排序的链表

2019-01-08  本文已影响0人  凌霄文强

题目描述

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

知识点

链表,归并


Qiang的思路

显然,这道题是一个归并问题,与归并排序中的归并过程不同的是对链表进行归并。但是可以采取相同的思路实现。

首先遍历两个链表,当有一个为空时停止遍历,然后分别去遍历两个链表,最后完成归并。

# -*- 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
        head=ListNode(None)
        result=head
        while pHead1!=None and pHead2!=None:
            if pHead1.val<pHead2.val:
                head.next=pHead1
                head=head.next
                pHead1=pHead1.next
            else:
                head.next=pHead2
                head=head.next
                pHead2=pHead2.next
        while pHead1!=None:
            head.next=pHead1
            head=head.next
            pHead1=pHead1.next
        while pHead2!=None:
            head.next=pHead2
            head=head.next
            pHead2=pHead2.next
        return result.next

作者原创,如需转载及其他问题请邮箱联系:lwqiang_chn@163.com
个人网站:https://www.myqiang.top

上一篇下一篇

猜你喜欢

热点阅读