题目:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseKGroup(head *ListNode, k int) *ListNode {
if k <= 1 || head == nil || head.Next == nil {
return head
}
start,end,next,oldEnd, count := head,head,head,head, 0
for loop := 1;end != nil; loop++{
if loop % k == 0 {
next,end.Next = end.Next, nil
newHead := reverseList(start)
if loop == k {
head = newHead
}else{
oldEnd.Next, oldEnd = newHead, start
}
start.Next,start,end = next,next,next
}else{
end = end.Next
count++
}
}
if count % k == 0 {
reverseList(start)
}
return head
}
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
for head != nil {
head.Next, prev, head = prev, head, head.Next
}
return prev
}
路漫漫其修远兮!