forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
59 lines (56 loc) · 854 Bytes
/
Solution.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
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseKGroup(head *ListNode, k int) *ListNode {
start := head
var h *ListNode = nil
var t *ListNode = nil
ok := false
if h, t, ok = revert(start, k); !ok {
return head
}
r := h
p := t
print(2, r)
for ok {
start = t.Next
h, t, ok = revert(start, k)
p.Next = h
p = t
}
return r
}
func revert(head *ListNode, k int) (h, t *ListNode, ok bool) {
c := head
if !check(c, k) {
return head, nil, false
}
t = head
var p *ListNode = nil
for k > 0 {
temp := head
head = head.Next
temp.Next = p
p = temp
k--
}
h = p
t.Next = head
ok = true
print(11, h)
return
}
func check(head *ListNode, k int) bool {
for k > 0 {
if head == nil {
return false
}
k--
head = head.Next
}
return true
}