update at 2022-05-22 23:54:36 by ehlxr
This commit is contained in:
commit
eb0bbbf53c
22
main.go
Normal file
22
main.go
Normal file
@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
. "github.com/ehlxr/leetcode-go/src"
|
||||
)
|
||||
|
||||
func main() {
|
||||
node5 := &Node{Value: 5, Next: nil}
|
||||
node4 := &Node{Value: 4, Next: node5}
|
||||
node3 := &Node{Value: 3, Next: node4}
|
||||
node2 := &Node{Value: 2, Next: node3}
|
||||
node1 := &Node{Value: 1, Next: node2}
|
||||
root := &Node{Value: 0, Next: node1}
|
||||
|
||||
// fmt.Printf("%v\n", root)
|
||||
|
||||
// fmt.Printf("%v\n", Reverse(root))
|
||||
|
||||
fmt.Printf("%v\n", ReverseKGroup(root, 2))
|
||||
}
|
15
src/node.go
Normal file
15
src/node.go
Normal file
@ -0,0 +1,15 @@
|
||||
package src
|
||||
|
||||
import "fmt"
|
||||
|
||||
type Node struct {
|
||||
Value int
|
||||
Next *Node
|
||||
}
|
||||
|
||||
func (n *Node) String() string {
|
||||
if n == nil {
|
||||
return "nil"
|
||||
}
|
||||
return fmt.Sprintf("{Value:%d Next:%+v}", n.Value, *n.Next)
|
||||
}
|
43
src/reverse.go
Normal file
43
src/reverse.go
Normal file
@ -0,0 +1,43 @@
|
||||
package src
|
||||
|
||||
func Reverse(root *Node) *Node {
|
||||
var pre, tmp *Node
|
||||
cur := root
|
||||
for cur != nil {
|
||||
tmp = cur.Next
|
||||
cur.Next = pre
|
||||
pre = cur
|
||||
cur = tmp
|
||||
|
||||
}
|
||||
return pre
|
||||
}
|
||||
|
||||
func ReverseKGroup(root *Node, k int) *Node {
|
||||
if root == nil {
|
||||
return root
|
||||
}
|
||||
n := root
|
||||
for i := 0; i < k; i++ {
|
||||
if n == nil {
|
||||
break
|
||||
}
|
||||
n = n.Next
|
||||
}
|
||||
tmp := ReverseN(root, n)
|
||||
root.Next = ReverseKGroup(n, k)
|
||||
return tmp
|
||||
}
|
||||
|
||||
func ReverseN(root *Node, n *Node) *Node {
|
||||
var pre, tmp *Node
|
||||
cur := root
|
||||
for cur != n {
|
||||
tmp = cur.Next
|
||||
cur.Next = pre
|
||||
pre = cur
|
||||
cur = tmp
|
||||
|
||||
}
|
||||
return pre
|
||||
}
|
Loading…
Reference in New Issue
Block a user