Go 语言程序逆序给定链表。
示例

解决此问题的方法
步骤 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("Input Linked List is: ")
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("Reversal of the input linked list is: ")
ReverseLinkedList(head)
}输出
Input Linked List is: 30 10 40 40 Reversal of the input linked list is: 40 40 10 30
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP