-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreverseKGroup.go
36 lines (33 loc) · 883 Bytes
/
reverseKGroup.go
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
package reversenodesinkgroup
// ListNode definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
func reverseKGroup(head *ListNode, k int) *ListNode {
if head != nil && k >= 2 {
return _reverseKGroup(head, k)
}
return head
}
func _reverseKGroup(head *ListNode, k int) *ListNode {
curr := head
count := 0
for ; curr != nil && count != k; count++ { // find the k+1 node
curr = curr.Next
}
if count != k { // if k+1 node is not found
return head
}
if curr != nil {
curr = _reverseKGroup(curr, k) // reverses list with k+1 node as head
}
// curr is k+1 node, count equal k+1
for ; count > 0; count-- { // reverses current k-group
next := head.Next // get the next head
head.Next = curr // moves curr to the next head
curr = head // moves head to curr
head = next // moves the next node to head
}
return curr
}