• 合并两个排序的链表


    题目描述

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

    解答

    # coding:utf-8
    # 创建结点
    class ListNode:
        def __init__(self,x, next=None):
            self.val = x
            self.next = next
    # 合并链表
    class Solution:
        def Merge(self, pHead1, pHead2):
            pro = head = ListNode(0)
            while pHead1 and pHead2:
                if pHead1.val < pHead2.val:
                    head.next = pHead1
                    pHead1 = pHead1.next
                else:
                    head.next = pHead2
                    pHead2 = pHead2.next
                head = head.next
            head.next = pHead1 or pHead2
            return pro.next
    
    
    pHead1 = None
    pHead2 = None
    # 创建链表
    for i in [6,4,2]:
        pHead1 = ListNode(i,pHead1)
        pHead2 = ListNode(i-1,pHead2)
    # 合并链表
    ret = Solution().Merge(pHead1,pHead2)
    验证
    while ret:
        print ret.val
        ret = ret.next

    结束

  • 相关阅读:
    display
    盒子模型
    css样式
    修改页面标题前的图标
    form表单
    html中列表
    代码书写格式
    dw中的超链接
    硬盘的访问,程序重定位和加载
    Bochs调试指令
  • 原文地址:https://www.cnblogs.com/aaronthon/p/13744792.html
Copyright © 2020-2023  润新知