-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode.21.swift
More file actions
63 lines (55 loc) · 1.58 KB
/
Copy pathLeetcode.21.swift
File metadata and controls
63 lines (55 loc) · 1.58 KB
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
class ListNode {
init(val: Int, next: ListNode? = nil) {
self.val = val
self.next = next
}
var val: Int
var next: ListNode?
}
class Solution {
func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
let dummyNode = ListNode(val: 0)
var currentNode: ListNode? = dummyNode
var currentList1 = list1
var currentList2 = list2
while let node1 = currentList1, let node2 = currentList2 {
if node1.val < node2.val {
currentNode?.next = node1
currentList1 = node1.next
} else {
currentNode?.next = node2
currentList2 = node2.next
}
currentNode = currentNode?.next
}
currentNode?.next = currentList1 ?? currentList2
return dummyNode.next
}
}
func convertArraytoLinkedlist(array: [Int]) -> ListNode {
var head: ListNode?
var tail: ListNode?
for val in array {
let node = ListNode(val: val)
if head == nil {
head = node
tail = node
} else {
tail?.next = node
tail = node
}
}
return head!
}
func forPrint(_ head: ListNode?) {
var current = head
while let node = current {
print(node.val, terminator: " ")
current = node.next
}
print()
}
let list1 = convertArraytoLinkedlist(array: [1, 2, 4])
let list2 = convertArraytoLinkedlist(array: [1, 3, 4])
let result = Solution().mergeTwoLists(list1, list2)
forPrint(result)