当索引位于第n个位置(即超出索引范围)时,Go语言程序更新第i个索引节点的值。
示例

解决此问题的方法
步骤1 − 定义一个接受链表头的方法。
步骤2 − 如果head == nil,则返回head。
步骤3 − 将索引初始化为i := 0。
步骤4 − 从其头部迭代给定的链表。
步骤5 − 如果索引i与给定索引(要更新的索引)匹配,则更新该节点。
步骤6 − 否则,返回head。
示例
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 := 10
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 10th index node, Linked List is: 30 10 40 40
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP