Skip to content

Commit 2f133cb

Browse files
committed
[Week4](gmlwls96) Merge two sorted lists
1 parent 9f7dd2f commit 2f133cb

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

merge-two-sorted-lists/gmlwls96.kt

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,43 @@
88
* }
99
*/
1010
class Solution {
11+
// 시간, 공간 : o(n+m),
1112
fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? {
12-
13+
var currentList1: ListNode? = list1
14+
var currentList2: ListNode? = list2
15+
val answerList = LinkedList<Int>()
16+
while (currentList1 != null || currentList2 != null) {
17+
when {
18+
currentList1 == null -> {
19+
answerList.offer(currentList2!!.`val`)
20+
currentList2 = currentList2.next
21+
}
22+
currentList2 == null -> {
23+
answerList.offer(currentList1.`val`)
24+
currentList1 = currentList1.next
25+
}
26+
currentList1.`val` <= currentList2.`val` -> {
27+
answerList.offer(currentList1.`val`)
28+
currentList1 = currentList1.next
29+
}
30+
currentList2.`val` < currentList1.`val` -> {
31+
answerList.offer(currentList2.`val`)
32+
currentList2 = currentList2.next
33+
}
34+
}
35+
}
36+
var answer: ListNode? = null
37+
var currentAnswer: ListNode? = null
38+
while (answerList.isNotEmpty()) {
39+
val num = answerList.poll()
40+
if (answer == null) {
41+
answer = ListNode(num)
42+
currentAnswer = answer
43+
} else {
44+
currentAnswer?.next = ListNode(num)
45+
currentAnswer = currentAnswer?.next
46+
}
47+
}
48+
return answer
1349
}
1450
}

0 commit comments

Comments
 (0)