zoukankan      html  css  js  c++  java
  • [Swift]LeetCode21. 合并两个有序链表 | Merge Two Sorted Lists

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/9697907.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

    Example:

    Input: 1->2->4, 1->3->4
    Output: 1->1->2->3->4->4

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

    示例:

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

    
    
     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     public var val: Int
     5  *     public var next: ListNode?
     6  *     public init(_ val: Int) {
     7  *         self.val = val
     8  *         self.next = nil
     9  *     }
    10  * }
    11  */
    12 class Solution {
    13     func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
    14         //如果一个链表为空,则直接返回另一个
    15         if l1==nil{return l2}
    16         if l2==nil{return l1}
    17         //判断链表大小,将小的链表连接到大的链表
    18         //使用递归,效率最高
    19         if l1!.val > l2!.val
    20         {
    21             //链表1大于链表2
    22             l2?.next=mergeTwoLists( l2?.next,l1)
    23             return l2
    24         }
    25         else
    26         {
    27             //链表2大于链表1
    28             l1?.next=mergeTwoLists(l1?.next,l2)
    29             return l1
    30         }
    31     }
    32 }
  • 相关阅读:
    Lua手册中的string.len 不解
    计算机词汇(Computer Glossary)
    Qt 信号和槽机制的优缺点
    多线程,什么时候该使用?
    Linux进行挂起和杀死挂起进程
    struct和class的区别
    Number of 1 Bits
    Pascal's Triangle
    Excel Sheet Column Title
    c++单向链表
  • 原文地址:https://www.cnblogs.com/strengthen/p/9697907.html
Copyright © 2011-2022 走看看