-
Notifications
You must be signed in to change notification settings - Fork 20
/
RotateList.kt
46 lines (38 loc) · 945 Bytes
/
RotateList.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
/**
* Given a list, rotate the list to the right by k places, where k is non-negative.
*
* Example:
*
* Given 1->2->3->4->5->NULL and k = 2,
*
* return 4->5->1->2->3->NULL.
*
* Accepted.
*/
class RotateList {
fun rotateRight(head: ListNode?, k: Int): ListNode? {
var anotherHead = head
var anotherK = k
if (anotherHead == null || anotherHead.next == null) {
return head
}
var node = anotherHead
var length = 1
while (node?.next != null) {
length++
node = node.next
}
node?.next = anotherHead // Form a circle
anotherK %= length
for (i in 0 until length - anotherK) {
node = node?.next
}
anotherHead = node?.next
node?.next = null
return anotherHead
}
data class ListNode(
var `val`: Int,
var next: ListNode? = null
)
}