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

更新於:2021 年 3 月 18 日

2K+ 檢視次數

開啟你的 職業道路

完成課程即可獲得認證

開始使用
廣告
© . All rights reserved.