Golang程序:在给定链表中将节点插入为第一个节点。


2022年2月22日, Learn eTutorial
1618

为了更好地理解这个示例,我们始终建议您学习下面列出的 Golang 编程 的基础主题

我们知道链表是节点的集合。每个节点都有自己的数据和一个指针,这个指针帮助您访问链表的下一个节点。这意味着链表中的所有元素都通过指针链接在一起。

假设我们想在给定链表的开头添加一个新节点,我们可以遵循这个Golang程序。在这个程序中,我们将重点关注如何使用GO语言将一个节点添加为给定链表的第一个节点。

有一个fmt包用于将一些标准库导入到程序中。使用内置函数fmt.println()在屏幕上打印任何内容,使用fmt.scanln()读取数据。这些函数定义在fmt包下。因此,我们需要导入“fmt”包才能使用这些函数。之后,打开main函数。我们将在main函数中完成整个程序,它是我们程序的起点。

这里我们使用一个结构体来定义一个节点。通过调用NewNode函数生成链表,该函数通过将数据分配给其节点值并更改节点指针作为下一个节点来创建节点。现在head是链表的起始节点。
通过调用TraverseLinkedList(head)函数显示链表中的所有节点,该函数从head开始遍历列表,直到我们找到引用值为NULL。

现在你有一个链表了。每当你想在给定链表中添加一个节点作为第一个节点时,通过使用fmt.scanln读取你想作为第一个节点添加的数据,并将其传递给AddFirstNode函数。这个函数定义了一个接受链表头的方法。检查head是否等于nil。如果是,创建一个新节点并返回该节点作为头。否则,更新输入链表的头。最后,通过调用TraverseLinkedList函数显示更新后的链表。

下面是在Go程序中用于在给定链表中添加第一个节点的步骤。

算法

步骤 1: 开始
步骤 2:定义一个节点结构体
步骤 3:通过调用函数 NewNode() 创建一个链表。这里的 head 是链表的起始节点。
步骤 4: 通过调用函数TraverseLinkedList(head)显示输入链表。
步骤 5: 读取您想要作为项目插入到链表中的新数据
步骤 6: 通过调用head = InsertFirstNode(head,item)在链表开头添加新节点。

步骤 7: 最后,使新节点成为列表的第一个节点
步骤 8: 通过调用函数TraverseLinkedList(head),在添加第一个节点后显示链表。
步骤 9:退出

实现NewNode(value int)的步骤

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

实现 TraverseLinkedList(head *Node) 的步骤

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

实现AddFirstNode(head *Node, data int)的步骤

步骤 1: 定义一个接受链表head的方法。
步骤 2: 如果head == nil,则创建一个新节点并返回该节点作为head。
步骤 3: 如果head不为nil,则更新输入链表的head,如下所示:

  • 为新节点ptr分配内存并将数据存储到ptr的数据部分。
  • 使新节点ptr的链接部分指向现有第一个节点,即列表的head。
  • 返回新节点ptr

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){
   temp := head
   for temp != nil {
      fmt.Printf("%d ", temp.value)
      temp = temp.next
   }
   fmt.Println()
}
func InsertFirstNode(head *Node, data int) *Node{
  if head == nil{
    head = NewNode(data, nil)
    return head
   }
   ptr := NewNode(data, nil)
  ptr.next = head
  fmt.Println("\nNode inserted\n") 
return ptr

}

func main(){
   head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
   fmt.Printf("Input Linked list is: ")
   TraverseLinkedList(head)
var item int;
fmt.Printf ("\nEnter the item which you want to insert?\n") 
        fmt.Scan(&item;)
       head = InsertFirstNode(head,item)  

   fmt.Println("After adding the first node, the linked list is: ")
   TraverseLinkedList(head)
}


                                      

输出

Input Linked list is: 30 10 40 40 

Enter the item which you want to insert?
90

Node inserted

After adding the first node, the linked list is: 
90 30 10 40 40