Golang程序 更新第i个索引节点的值,当索引在2的时候,也就是中间索引
例子
解决这个问题的方法
第1步 - 定义一个方法,接受一个链表的头部。
第2步 - 如果 head == nil,返回 head。
第3步 --初始化索引为i :=0。
第4步 --从头开始迭代给定的链表。
第5步 – 如果索引i与给定的索引相匹配(要更新),那么更新该节点。
第6步 - 否则,返回头部。
例子
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 UpdateKthIndexNode(head *Node, index , data int) *Node{
if head == nil{
return head
}
i := 0
temp := head
for temp != nil{
if i == index{
temp.value = data
break
}
i++
temp = temp.next
}
return head
}
func main(){
head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
fmt.Printf("Input Linked list is: ")
TraverseLinkedList(head)
index := 2
head = UpdateKthIndexNode(head, index, 15)
fmt.Printf("Update %dth index node, Linked List is: ", index)
TraverseLinkedList(head)
}
输出
Input Linked list is: 30 10 40 40
Update 2th index node, Linked List is: 30 10 15 40