Golang 程序用于反转给定的链接列表。
go programmingserver side programmingprogramming
示例
解决此问题的方法
步骤 1 − 定义一个接受链接列表头的方法。
步骤 2 − 如果 head == nil,则返回;否则,递归调用 ReverseLinkedList。
步骤 3 −在末尾打印 head.value。
示例
package main import "fmt" type Node struct { value int next *Node } func NewNode(value int, next *Node) *Node{ var n Node n.value = value n.next = next return &n } func TraverseLinkedList(head *Node){ fmt.Printf("输入链表为:") temp := head for temp != nil { fmt.Printf("%d ", temp.value) temp = temp.next } fmt.Println() } func ReverseLinkedList(head *Node){ if head == nil{ return } ReverseLinkedList(head.next) fmt.Printf("%d ", head.value) } func main(){ head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil)))) TraverseLinkedList(head) fmt.Printf("输入链表的反转为: ") ReverseLinkedList(head) }
输出
输入链表为: 30 10 40 40 输入链表的反转为: 40 40 10 30