Golang程序 更新一个链接列表中的第一个节点的值
例子
解决这个问题的方法
第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("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