题解 | #合并两个排序的链表#

合并两个排序的链表

http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

# -*- 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 pHead1 == None:
            return pHead2
        if pHead2 == None:
            return pHead1
        
        newHead = None
        if pHead1.val < pHead2.val:
            newHead = ListNode(pHead1.val)
            pHead1 = pHead1.next
        else:
            newHead = ListNode(pHead2.val)
            pHead2 = pHead2.next
        p = newHead
        while True:
            if pHead1 is None or pHead2 is None:
                break
            while True:
                if pHead1 and pHead2 and pHead1.val < pHead2.val:
#                     print("111", pHead1.val)
                    p.next = ListNode(pHead1.val)
                    pHead1 = pHead1.next
                    p = p.next
                else:
                    break
            while True:
                if pHead1 and pHead2 and pHead2.val <= pHead1.val:
#                     print("222", pHead1.val)
                    
                    p.next = ListNode(pHead2.val)
                    pHead2 = pHead2.next
                    p = p.next
                else:
                    break
        if pHead1 is None:
            p.next = pHead2
        if pHead2 is None:
            p.next = pHead1            
        return newHead
        
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务