欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

两个链表归并

程序员文章站 2022-07-13 17:50:29
...

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

两个链表归并

# -*- 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
        
        temp_head = None         # 辅助链表的当前位置
        
        
        if pHead1 == None:
            return pHead2
        if pHead2 == None:
            return pHead1
        
        if pHead1.val<=pHead2.val:
            temp_head = pHead1
            pHead1 = pHead1.next
        else:
            temp_head = pHead2
            pHead2 = pHead2.next
        
        head = temp_head        # 辅助链表的头位置
        
        while pHead1!=None and pHead2!=None:
            if (pHead1.val<=pHead2.val):
                temp_head.next = pHead1
                pHead1 = pHead1.next
                temp_head = temp_head.next
            else:
                temp_head.next = pHead2
                pHead2 = pHead2.next
                temp_head = temp_head.next
        
        if pHead1==None:
            temp_head.next = pHead2
        if pHead2 == None:
            temp_head.next = pHead1
            
        return head            # 返回辅助链表的头位置
           

 

相关标签: 数据结构