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
            
  • 相关阅读:
    Linux用户组管理及用户权限3
    MySQL预处理和事务
    MySQL-子查询和多表联查
    Mysql-分组和聚合函数
    LNMP搭建
    apache-虚拟主机配置
    Apache-重写
    apache配置文件详解
    vim使用
    php-curl_init函数
  • 原文地址:https://www.cnblogs.com/wangzhihang/p/11790787.html
Copyright © 2011-2022 走看看