Golang 程式以更新連結串列中的最後節點值。


示例

解決此問題的辦法

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

步驟 2 − 如果 head == nil,則返回該頭部。

步驟 3 − 否則,將最後節點的值更新為 41。

示例

 動態演示

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 UpdateLastNodeValue(head *Node, data int) *Node{
   if head == nil{
      return head
   }
   temp := head
   for temp.next != nil{
      temp = temp.next
   }
   temp.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 = UpdateLastNodeValue(head, 41)
   fmt.Printf("After updating last node value, linked list is: ")
   TraverseLinkedList(head)
}

輸出

Input Linked list is: 30 10 40 40
After updating last node value, linked list is: 30 10 40 41

更新於: 2021 年 3 月 18 日

253 次瀏覽

開啟您的 職業生涯

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.