-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.go
68 lines (59 loc) · 1.12 KB
/
run.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package pairs
import (
"github.com/itcuihao/leetcode-go/structure"
)
//import "leetcode-go/structure"
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
// 时间复杂度:0(n)
// 空间复杂度:0(1)
func reverseKGroup(head *structure.ListNode, k int) *structure.ListNode {
if head == nil || head.Next == nil {
return head
}
count := 0
cur := head
for cur != nil && count != k {
cur = cur.Next
count++
}
if count == k {
cur = reverseKGroup(cur, k)
for count > 0 {
count--
tmp := head.Next
head.Next = cur
cur = head
head = tmp
}
head = cur
}
return head
}
func reverseKGroup2(head *structure.ListNode, k int) *structure.ListNode {
node := head
for i := 0; i < k; i++ {
if node == nil {
return head
}
node = node.Next
}
newHead := reverse(head, node)
head.Next = reverseKGroup2(node, k)
return newHead
}
func reverse(first *structure.ListNode, last *structure.ListNode) *structure.ListNode {
prev := last
for first != last {
tmp := first.Next
first.Next = prev
prev = first
first = tmp
}
return prev
}