-
Notifications
You must be signed in to change notification settings - Fork 21
/
MergeTwoSortedLists.swift
65 lines (53 loc) 路 1.66 KB
/
MergeTwoSortedLists.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
// MergeTwoSortedLists.swift
// LeetCode
//
// Created by 榛庤档澶儙 on 07/12/2017.
// Copyright 漏 2017 lizhaotailang. All rights reserved.
//
// 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
//
// Accepted. See [MergeTwoSortedListsTests](./LeetCodeTests/MergeTwoSortedListsTests.swift) for test cases.
//
import Foundation
class MergeTwoSortedLists {
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var node1 = l1
var node2 = l2
var result: ListNode? = ListNode(0)
let fakeHead = result
while node1 != nil && node2 != nil {
if node1!.val <= node2!.val {
result?.next = ListNode(node1!.val)
node1 = node1!.next
} else {
result?.next = ListNode(node2!.val)
node2 = node2?.next
}
result = result?.next
}
if node1 == nil {
result?.next = node2
} else {
result?.next = node1
}
return fakeHead!.next
}
public class ListNode: Equatable {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
public static func ==(lhs: MergeTwoSortedLists.ListNode, rhs: MergeTwoSortedLists.ListNode) -> Bool {
return lhs.val == rhs.val && lhs.next == rhs.next
}
}
}