[Swift]LeetCode21. 合併兩個有序鏈表 | Merge Two Sorted Lists

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-bvjdczqu-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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.node

Example:git

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

將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是經過拼接給定的兩個鏈表的全部節點組成的。 github

示例:微信

輸入: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 }
相關文章
相關標籤/搜索