Golang 程序更新链接列表中的第一个节点值。

go programmingserver side programmingprogramming

示例

解决此问题的方法

步骤 1 − 定义一个接受链接列表头部的方法。

步骤 2 − 如果 head == nil,则返回头部。

步骤 3 − 否则,将第一个节点值更新为 29。

示例

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 UpdateFirstNodeValue(head *Node, data int) *Node{
   if head == nil{
      return head
   }
   head.value = data
   return head
}
func main(){
   head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
   fmt.Printf("输入链表为:")
   TraverseLinkedList(head)
   head = UpdateFirstNodeValue(head, 29)
   fmt.Printf("更新第一个节点值后,链表为:")
   TraverseLinkedList(head)
}

输出

输入链表为:30 10 40 40
更新第一个节点值后,链表为:29 10 40 40

相关文章