-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0025-reverse-nodes-in-k-group.kt
55 lines (44 loc) · 1.61 KB
/
0025-reverse-nodes-in-k-group.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
54
55
package kotlin
class Solution {
private fun reverse(startNode: ListNode?, endNode: ListNode?): ListNode? {
if (startNode == null) return null
var currentNode = startNode
var temp: ListNode?
var previousNode: ListNode? = null
while (currentNode != null) {
temp = currentNode.next
currentNode.next = previousNode
previousNode = currentNode
if (currentNode === endNode) break
currentNode = temp
}
return previousNode
}
private fun getKthNode(headNode: ListNode, k: Int): ListNode? {
var currentNode: ListNode? = headNode
var counter = 1
while (currentNode != null && counter < k) {
counter++
currentNode = currentNode.next
}
return currentNode
}
fun reverseKGroup(head: ListNode?, k: Int): ListNode? {
if (head == null) return null
val dummyNode = ListNode(-1).apply { next = head }
var kthNode: ListNode?
var currentNode = head
var previousNodeOfCurrentGroup = dummyNode
var nextNodeOfCurrentGroup: ListNode?
while (currentNode != null) {
kthNode = getKthNode(currentNode, k)
if (kthNode == null) break
nextNodeOfCurrentGroup = kthNode.next
previousNodeOfCurrentGroup.next = reverse(startNode = currentNode, endNode = kthNode)
currentNode.next = nextNodeOfCurrentGroup
previousNodeOfCurrentGroup = currentNode
currentNode = nextNodeOfCurrentGroup
}
return dummyNode.next
}
}