|
| 1 | +/** |
| 2 | + * Example: |
| 3 | + * var li = ListNode(5) |
| 4 | + * var v = li.`val` |
| 5 | + * Definition for singly-linked list. |
| 6 | + * class ListNode(var `val`: Int) { |
| 7 | + * var next: ListNode? = null |
| 8 | + * } |
| 9 | + */ |
| 10 | +class Solution { |
| 11 | + // 시간, 공간 : o(n+m), |
| 12 | + fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { |
| 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 |
| 49 | + } |
| 50 | +} |
0 commit comments