Golang 反转给定链表的程序


2022年12月28日, Learn eTutorial
2411

什么是链表?

链表是我们计算机编程中遇到的线性数据结构之一。它有一堆节点,每个节点包含数据和指向下一个节点的指针。我们可以看到“LL”中的所有元素都通过指针连接起来。

如何在 Go 程序中使用递归反转链表?

为了反转链表,我们导入了“fmt”包,以便在 GO 程序中包含一些标准库。为了使用这些库函数,我们需要导入“fmt”包。之后主函数开始,并在其中执行整个程序。

这个 Go 程序定义了一个方法,它接受链表的头部。要显示输入链表的反转,请调用函数 ReverseLinkedList(head)。此函数将检查 head 是否等于 nil。如果是,则返回;否则,递归调用 ReverseLinkedList。最后,在末尾显示头节点值。

算法

步骤 1:开始
步骤 2:定义节点的结构
步骤 3:通过调用函数 NewNode() 创建一个链表。这里的 head 是起始节点。
步骤 4:调用函数 TraverseLinkedList(head) 显示输入链表。
步骤 5:通过调用函数 ReverseLinkedList(head) 显示输入链表的反转
步骤 6:退出

实现 NewNode(value int) 的步骤

步骤 1:声明变量 n 为 Node 类型。
步骤 2:通过将数据分配给节点值并将节点的指针更改为下一个节点来创建节点 n
步骤 3:返回节点 n

实现 TraverseLinkedList(head *Node) 的步骤

步骤 1:通过遍历从 head 开始的列表,直到我们找到引用值为 NULL,从而显示链表中的所有节点。

实现 ReverseLinkedList(head *Node) 的步骤

步骤 1:检查条件 head == nil,如果是,则返回;否则,递归调用 ReverseLinkedList
步骤 2:在末尾显示 head 的值。
 


为了在 GO 中反转链表,我们使用了以下概念。我们建议您学习这些概念以更好地理解。

Golang 源代码

                                          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(80, NewNode(70, NewNode(55, NewNode(90, nil))))
   TraverseLinkedList(head)
   fmt.Printf("Reversal of the input linked list is: ")
   ReverseLinkedList(head)
}
                                      

输出

Input Linked List is: 80 70 55 90 
Reversal of the input linked list is: 90 55 70 80