Skip to content

Commit 043df5a

Browse files
committed
8주차 제출
1 parent be3b1fa commit 043df5a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

merge-two-sorted-lists/jdalma.kt

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package leetcode_study
2+
3+
import io.kotest.matchers.shouldBe
4+
import org.junit.jupiter.api.Test
5+
6+
class `merge-two-sorted-lists` {
7+
8+
data class ListNode(
9+
var `val`: Int,
10+
var next: ListNode? = null
11+
)
12+
13+
/**
14+
* TC: O(n + m), SC: O(1)
15+
*/
16+
fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? {
17+
var (l1, l2) = list1 to list2
18+
var current = ListNode(-1)
19+
val result: ListNode = current
20+
21+
while (l1 != null && l2 != null) {
22+
if (l1.`val` < l2.`val`) {
23+
current.next = l1
24+
l1 = l1.next
25+
} else {
26+
current.next = l2
27+
l2 = l2.next
28+
}
29+
current.next?.let { current = it }
30+
}
31+
32+
if (l1 != null) current.next = l1
33+
if (l2 != null) current.next = l2
34+
35+
return result.next
36+
}
37+
38+
@Test
39+
fun `두 개의 리스트 노드를 정렬하여 병합한다`() {
40+
mergeTwoLists(
41+
ListNode(1,ListNode(2,ListNode(4))),
42+
ListNode(1,ListNode(3,ListNode(4)))
43+
) shouldBe ListNode(1,ListNode(1,ListNode(2, ListNode(3, ListNode(4, ListNode(4))))))
44+
}
45+
}

0 commit comments

Comments
 (0)