zoukankan      html  css  js  c++  java
  • 【leetcode 简单】 第七题 合并两个有序链表

    将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

    示例:

    输入:1->2->4, 1->3->4
    输出:1->1->2->3->4->4
    


    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
        def __repr__(self):# 显示方式
            return "{}->{}".format(self.val,self.next)
    
    
    class Solution:
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            if not l1:return l2
            if not l2:return l1
            current =tmp= ListNode(0) #current 和 tmp 指向同一个头结点
            while l1 and l2:
                if l1.val < l2.val:
                    current.next = l1
                    l1=l1.next
                else:
                    current.next = l2
                    l2=l2.next
    
                current = current.next #单向链表,指向最后一个结点"指针"
    
            current.next = l1 or l2 #current链表最后一个结点的"指针"指向l1或者l2的头结点
            return tmp.next  #current的指针指向了l1或者l2的头结点,返回tmp完整链表
  • 相关阅读:
    mysql时间操作函数和存储过程
    puppet foreman
    mysql c haracter
    socket
    socket 网摘
    网络安全
    sqlite3 C接口
    spring 配置文件XSD地址
    programData
    网络安全数据包分析
  • 原文地址:https://www.cnblogs.com/flashBoxer/p/9438935.html
Copyright © 2011-2022 走看看