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

题目描述

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

思路

分别给两个链表定义一个当前结点的指针,比较两个结点大小,把小的一个几点加入到最后的结果中,如果其中一个链表遍历到头了,就把另外那个链表再加入到最后的结果当中

代码

# -*- 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:
            head = pHead1
            cur = head
            pHead1 = pHead1.next
        else:
            head = pHead2
            cur = head
            pHead2 = pHead2.next
        while pHead1 and pHead2:
            if pHead1.val < pHead2.val:
                cur.next = pHead1
                cur = cur.next
                pHead1 = pHead1.next
            else:
                cur.next = pHead2
                cur = cur.next
                pHead2 = pHead2.next
        if pHead1:
            cur.next = pHead1
        else:
            cur.next = pHead2
        return head
        

 

posted @ 2019-11-04 10:30  小小文艺范  阅读(158)  评论(0编辑  收藏  举报

contact me

email:78910421@qq.com