-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC_2181.kt
53 lines (51 loc) · 1.35 KB
/
LC_2181.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
51
52
53
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class LC_2181 {
fun mergeNodes(head: ListNode?): ListNode? {
var res: ListNode? = null
var tail: ListNode? = null
var curNode: ListNode? = head
var tmp = 0
while (true) {
if (curNode == null) break
when (val v = curNode.`val`) {
0 -> {
if (tmp != 0) {
val newNode = ListNode(tmp)
if (res == null) res = newNode
if (tail == null) tail = newNode
else {
tail.next = newNode
tail = newNode
}
tmp = 0
}
}
else -> tmp += v
}
curNode = curNode?.next
}
return res
}
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
fun main() {
val sol = LC_2181()
val head = ListNode(0)
var tail = head
listOf(3,1,0,4,5,2,0).forEach {
val tmp = ListNode(it)
tail.next = tmp
tail = tmp
}
sol.mergeNodes(head)
}