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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP