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