Skip to content

Commit

Permalink
8주차 제출
Browse files Browse the repository at this point in the history
  • Loading branch information
jdalma committed Sep 30, 2024
1 parent be3b1fa commit 043df5a
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions merge-two-sorted-lists/jdalma.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package leetcode_study

import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test

class `merge-two-sorted-lists` {

data class ListNode(
var `val`: Int,
var next: ListNode? = null
)

/**
* TC: O(n + m), SC: O(1)
*/
fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? {
var (l1, l2) = list1 to list2
var current = ListNode(-1)
val result: ListNode = current

while (l1 != null && l2 != null) {
if (l1.`val` < l2.`val`) {
current.next = l1
l1 = l1.next
} else {
current.next = l2
l2 = l2.next
}
current.next?.let { current = it }
}

if (l1 != null) current.next = l1
if (l2 != null) current.next = l2

return result.next
}

@Test
fun `두 개의 리스트 노드를 정렬하여 병합한다`() {
mergeTwoLists(
ListNode(1,ListNode(2,ListNode(4))),
ListNode(1,ListNode(3,ListNode(4)))
) shouldBe ListNode(1,ListNode(1,ListNode(2, ListNode(3, ListNode(4, ListNode(4))))))
}
}

0 comments on commit 043df5a

Please sign in to comment.