-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathRemoveDuplicatesFromSortedList.kt
50 lines (44 loc) · 1.39 KB
/
RemoveDuplicatesFromSortedList.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package questions
import _utils.UseCommentAsDocumentation
import questions.common.LeetNode
import utils.assertIterableSame
/**
* Given the head of a sorted linked list, delete all duplicates such
* that each element appears only once. Return the linked list sorted as well.
*
* [source](https://leetcode.com/problems/remove-duplicates-from-sorted-list/)
*/
@UseCommentAsDocumentation
private fun deleteDuplicates(head: LeetNode?): LeetNode? {
if (head == null) return head
var current: LeetNode? = head.next
var prev: LeetNode? = head
while (current != null) {
if (prev!!.`val` == current.`val`) {
prev.next = current.next
current = prev.next
} else {
prev = current
current = prev.next
}
}
return head
}
fun main() {
run {
val node = LeetNode.from(intArrayOf(1, 1, 2, 2))
assertIterableSame(listOf(1, 2), deleteDuplicates(node)!!.toList())
}
run {
val node = LeetNode.from(intArrayOf(1, 1, 1))
assertIterableSame(listOf(1), deleteDuplicates(node)!!.toList())
}
run {
val node = LeetNode.from(intArrayOf(1, 1, 2, 3, 3))
assertIterableSame(listOf(1, 2, 3), deleteDuplicates(node)!!.toList())
}
run {
val node = LeetNode.from(intArrayOf(1, 1, 2))
assertIterableSame(listOf(1, 2), deleteDuplicates(node)!!.toList())
}
}