- Swift LeetCode 系列之 19: mergeTwoL
- Swift LeetCode 系列之 7: Reverse In
- Swift LeetCode 系列之 19: Remove Nt
- Swift vs. Kotlin 漫谈系列之接口
- Best Time to Buy and Sell Stock
- Swift LeetCode 系列之46: permutatio
- Swift LeetCode 系列之 1: TwoSum
- Swift LeetCode 系列之 13: roman-to-
- Swift LeetCode 系列之9: palindrome-
- Swift LeetCode 系列之4: Median of T
https://leetcode.com/problems/merge-two-sorted-lists/description/
将两条有序的链表合并为一条有序的链表
时间复杂度0(m+n) m, n 为链表的长度
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var l1 = l1
var l2 = l2
var result = ListNode(0)
var help = result
while(l1 != nil && l2 != nil) {
if l1!.val > l2!.val {
help.next = l2
l2 = l2!.next
}else {
help.next = l1
l1 = l1!.next
}
help = help.next!
}
if l1 != nil {
help.next = l1
}
if l2 != nil {
help.next = l2
}
return result.next
}
}
网友评论