-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0021-merge-two-sorted-lists.swift
53 lines (46 loc) · 1.44 KB
/
0021-merge-two-sorted-lists.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
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func mergeTwoLists(
_ list1: ListNode?,
_ list2: ListNode?
) -> ListNode? {
var dummyNode: ListNode? = ListNode(-10000)
var resultNode = dummyNode
var itr1 = list1
var itr2 = list2
while itr1 != nil && itr2 != nil {
let v1 = itr1?.val ?? Int.max
let v2 = itr2?.val ?? Int.max
if v1 < v2 {
resultNode?.next = itr1
itr1 = itr1?.next
} else {
resultNode?.next = itr2
itr2 = itr2?.next
}
resultNode = resultNode?.next
}
// itr1 is available only
while itr1 != nil {
resultNode?.next = itr1
resultNode = resultNode?.next
itr1 = itr1?.next
}
// itr2 is available only
while itr2 != nil {
resultNode?.next = itr2
resultNode = resultNode?.next
itr2 = itr2?.next
}
return dummyNode?.next
}
}