File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments