-
Notifications
You must be signed in to change notification settings - Fork 0
/
rev_linked_list.go
99 lines (89 loc) · 1.6 KB
/
rev_linked_list.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
package main
import (
"fmt"
"log"
"strings"
)
type TestData struct {
A []int
B []int
K int
}
type ListNode struct {
Val int
Next *ListNode
}
func main() {
testData := []TestData{
TestData{A: []int{1, 2}, B: []int{}, K: 2},
TestData{A: []int{1, 2, 3}, B: []int{}, K: 2},
}
for _, testSet := range testData {
log.Println(testSet)
var head *ListNode
var prev *ListNode
for _, elem := range testSet.A {
newNode := ListNode{Val: elem}
if head == nil {
head = &newNode
}
if prev != nil {
prev.Next = &newNode
prev = prev.Next
} else {
prev = &newNode
}
// log.Println(newNode, head, prev)
}
printList(head)
start := reverseKGroup(head, testSet.K)
printList(start)
}
log.Println("Finish")
}
func reverseKGroup(head *ListNode, k int) *ListNode {
var start *ListNode
curHead := head
curTail := head
for {
i := 1
curTail = curHead
log.Println("I", i, curTail)
for i <= k && curTail.Next != nil {
curTail = curTail.Next
i++
}
log.Println("I", i, curTail)
// not enough elements remain in the list
if i < k {
return start
}
nextHead := curTail.Next
reverseK(curHead, k)
// printList(curTail)
curHead.Next = nextHead
if start == nil {
start = curTail
}
}
}
func reverseK(start *ListNode, k int) {
log.Println("RevK", start, k)
a := start
var prev *ListNode
for k > 0 {
tmp := a.Next
a.Next = prev
prev = a
a = tmp
k--
}
}
func printList(start *ListNode) {
a := []string{}
for start != nil {
a = append(a, fmt.Sprintf("%d", start.Val))
start = start.Next
}
log.Println("List:", strings.Join(a, "->"))
}