zoukankan      html  css  js  c++  java
  • 剑指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
            
  • 相关阅读:
    ES6笔记
    JavaScriptOOP (三)
    JavaScriptOOP(二)
    JavaScriptOOP(一)
    基于vue-cli 将webpack3 升级到 webpack4 配置
    JavaScript 中 call,apply 和 bind
    vue 2.6 更新变动
    JavaScript严格模式
    vue 修饰符 整理
    webpack打包将配置文件单独抽离不压缩打包
  • 原文地址:https://www.cnblogs.com/wangzhihang/p/11790787.html
Copyright © 2011-2022 走看看