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