Skip to content

Commit 84bc5b6

Browse files
committed
merge two sorted lists
1 parent 05092cc commit 84bc5b6

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class Solution {
2+
func mergeTwoListsIterative(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
3+
var iterList1 = list1
4+
var iterList2 = list2
5+
6+
var dummy = ListNode()
7+
var merged = dummy
8+
9+
while iterList1 != nil && iterList2 != nil,
10+
let list1 = iterList1,
11+
let list2 = iterList2 {
12+
if list1.val < list2.val {
13+
merged.next = list1
14+
iterList1 = list1.next
15+
} else {
16+
merged.next = list2
17+
iterList2 = list2.next
18+
}
19+
20+
guard let next = merged.next else {
21+
break
22+
}
23+
24+
merged = next
25+
}
26+
27+
merged.next = iterList1 ?? iterList2
28+
29+
return dummy.next
30+
31+
//시간복잡도 O(m+n)
32+
//공간복잡도 O(1)
33+
}
34+
35+
func mergeTwoListsRecursion(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
36+
guard var list1 = list1 else {
37+
return list2
38+
}
39+
40+
guard var list2 = list2 else {
41+
return list1
42+
}
43+
44+
if list1.val < list2.val {
45+
list1.next = mergeTwoListsRecursion(list1.next, list2)
46+
return list1
47+
} else {
48+
list2.next = mergeTwoListsRecursion(list1, list2.next)
49+
return list2
50+
}
51+
52+
//시간 복잡도 O(m+n)
53+
//공간 복잡도 O(m+n)
54+
}
55+
}
56+

0 commit comments

Comments
 (0)