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
| func reverseKGroup(head *ListNode, k int) *ListNode {
if head == nil || k == 1 {
return head
}
tail := head
for i := 0; i < k; i++ {
if tail == nil {
return head
}
tail = tail.Next
}
newHead := reverse(head, tail)
head.Next = reverseKGroup(tail, k)
return newHead
}
func reverse(head *ListNode, tail *ListNode) *ListNode {
var pre *ListNode
cur := head
for cur != tail {
next := cur.Next
cur.Next = pre
pre = cur
cur = next
}
return pre
}
|