-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse-nodes-in-k-group.go
111 lines (103 loc) · 1.9 KB
/
reverse-nodes-in-k-group.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"fmt"
"bytes"
)
type ListNode struct {
Val int
Next *ListNode
}
func (head *ListNode) String() string {
var buf = bytes.Buffer{}
for n := head; n != nil; n = n.Next {
if n != head {
buf.WriteString(" -> ")
}
buf.WriteString(fmt.Sprintf("[%d]", n.Val))
}
return buf.String()
}
func reverseKGroup(head *ListNode, k int) *ListNode {
if head == nil || k <= 1 {
return head
}
length := 0
for n := head; n != nil; n = n.Next {
length++
}
if k > length {
return head
}
if k == length {
tail := head
for ; tail != nil && tail.Next != nil; tail = tail.Next {
}
h, _ := doReverse(head, tail)
return h
}
group := (length-1)/k + 1
groupList := make([]struct {
h *ListNode
t *ListNode
}, group)
node := head
for g := 0; g < group; g++ {
var pair = struct {
h *ListNode
t *ListNode
}{node, nil}
for i := 0; node != nil; node = node.Next {
if i >= k-1 {
pair.t = node
break
}
i++
}
if node != nil {
node = node.Next
}
if pair.t != nil {
pair.t.Next = nil
}
groupList[g] = pair
}
for i := range groupList {
gg := groupList[i]
h, t := doReverse(gg.h, gg.t)
gg.h = h
gg.t = t
groupList[i] = gg
}
for i := 0; i < group-1; i++ {
next := groupList[i+1]
if next.h != nil {
groupList[i].t.Next = next.h
} else {
groupList[i].t.Next = next.t
}
}
return groupList[0].h
}
func doReverse(head, tail *ListNode) (*ListNode, *ListNode) {
if head == nil || tail == nil || head == tail {
return tail, head
}
pre, cur, next := head, head.Next, head.Next.Next
for {
cur.Next = pre
if cur == tail {
break
}
pre = cur
cur = next
next = next.Next
}
head.Next = nil
return tail, head
}
func main() {
h := &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, nil}}}}}
fmt.Println(h)
fmt.Println("k = ", 2, "\t", reverseKGroup(h, 2))
fmt.Println("k = ", 3, "\t", reverseKGroup(h, 3))
}