zoukankan      html  css  js  c++  java
  • LeetCode:21. 合并两个有序链表

    1、题目描述

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

    示例:

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

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

    2、题解

    2.1、解法一

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            if l1 == None:
                return l2
            if l2 == None:
                return l1
            
            left,right = l1,l2
            if left.val < right.val:
                new = left
                left = left.next
            else:
                new = right
                right = right.next
    
            node = new
            while left and right:
                if left.val <= right.val:
                    node.next = left
                    left = left.next
                else:
                    node.next = right
                    right = right.next
                node = node.next
    
            while left:
                node.next = left
                left = left.next
                node = node.next
    
            while right:
                node.next = right
                right = right.next
                node = node.next
    
            return new
    

      

     
  • 相关阅读:
    spring boot 与 spring cloud 版本映射
    Java锁
    并发编程(二)
    并发工具类和线程池
    并发编程
    Map双列集合(二)
    Map双列集合(一)
    单列集合List
    类加载
    JVM字节码与代码优化
  • 原文地址:https://www.cnblogs.com/bad-robot/p/10065004.html
Copyright © 2011-2022 走看看