剑指offer_合并两个排序的链表

题目描述

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

# -*- 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    
        phead = ListNode(0)
        pHead = phead
        while pHead1 and pHead2:
            if pHead1.val>pHead2.val:
                pHead.next = pHead2
                pHead2 = pHead2.next
                
            else:
                pHead.next = pHead1
                pHead1 = pHead1.next
            pHead = pHead.next
        if not pHead1:
            pHead.next = pHead2
        if not pHead2:
            pHead.next = pHead1
        return phead.next

猜你喜欢

转载自blog.csdn.net/Alicehzj/article/details/82667051