reverse linkedlist
This commit is contained in:
parent
eb0bbbf53c
commit
dc5d8f0dfd
18
main.go
18
main.go
@ -7,16 +7,16 @@ import (
|
||||
)
|
||||
|
||||
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}
|
||||
node5 := &ListNode{Val: 5, Next: nil}
|
||||
node4 := &ListNode{Val: 4, Next: node5}
|
||||
node3 := &ListNode{Val: 3, Next: node4}
|
||||
node2 := &ListNode{Val: 2, Next: node3}
|
||||
node1 := &ListNode{Val: 1, Next: node2}
|
||||
root := &ListNode{Val: 0, Next: node1}
|
||||
|
||||
// fmt.Printf("%v\n", root)
|
||||
fmt.Printf("%v\n", root)
|
||||
|
||||
// fmt.Printf("%v\n", Reverse(root))
|
||||
|
||||
fmt.Printf("%v\n", ReverseKGroup(root, 2))
|
||||
fmt.Printf("%v\n", ReverseRec(root))
|
||||
// fmt.Printf("%v\n", ReverseKGroup(root, 2))
|
||||
}
|
||||
|
10
src/node.go
10
src/node.go
@ -2,14 +2,14 @@ package src
|
||||
|
||||
import "fmt"
|
||||
|
||||
type Node struct {
|
||||
Value int
|
||||
Next *Node
|
||||
type ListNode struct {
|
||||
Val int
|
||||
Next *ListNode
|
||||
}
|
||||
|
||||
func (n *Node) String() string {
|
||||
func (n *ListNode) String() string {
|
||||
if n == nil {
|
||||
return "nil"
|
||||
}
|
||||
return fmt.Sprintf("{Value:%d Next:%+v}", n.Value, *n.Next)
|
||||
return fmt.Sprintf("{Val:%d Next:%+v}", n.Val, *n.Next)
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
package src
|
||||
|
||||
func Reverse(root *Node) *Node {
|
||||
var pre, tmp *Node
|
||||
func Reverse(root *ListNode) *ListNode {
|
||||
var pre, tmp *ListNode
|
||||
cur := root
|
||||
for cur != nil {
|
||||
tmp = cur.Next
|
||||
@ -13,7 +13,20 @@ func Reverse(root *Node) *Node {
|
||||
return pre
|
||||
}
|
||||
|
||||
func ReverseKGroup(root *Node, k int) *Node {
|
||||
func ReverseRec(root *ListNode) *ListNode {
|
||||
if root == nil || root.Next == nil {
|
||||
return root
|
||||
}
|
||||
|
||||
res := ReverseRec(root.Next)
|
||||
root.Next.Next = root
|
||||
root.Next = nil
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
/* K 个一组翻转链表 */
|
||||
func ReverseKGroup(root *ListNode, k int) *ListNode {
|
||||
if root == nil {
|
||||
return root
|
||||
}
|
||||
@ -29,8 +42,9 @@ func ReverseKGroup(root *Node, k int) *Node {
|
||||
return tmp
|
||||
}
|
||||
|
||||
func ReverseN(root *Node, n *Node) *Node {
|
||||
var pre, tmp *Node
|
||||
/* 反转链表到指定节点 */
|
||||
func ReverseN(root *ListNode, n *ListNode) *ListNode {
|
||||
var pre, tmp *ListNode
|
||||
cur := root
|
||||
for cur != n {
|
||||
tmp = cur.Next
|
||||
|
Loading…
Reference in New Issue
Block a user