★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(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 }