使用 Go 語言程式更新連結串列中的第一個節點值。


示例

解決此問題的辦法

步驟 1 − 定義一個方法,接受連結串列的頭部。

步驟 2 − 如果頭部為 null,則返回頭部。

步驟 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("Input Linked list is: ")
   TraverseLinkedList(head)
   head = UpdateFirstNodeValue(head, 29)
   fmt.Printf("After updating first node value, linked list is: ")
   TraverseLinkedList(head)
}

輸出

Input Linked list is: 30 10 40 40
After updating first node value, linked list is: 29 10 40 40

更新日期:2021-03-18

166 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告