Go语言程序,用于更新第 i 个索引节点的值,当索引为 2 时,即中间索引。
示例

解决此问题的方法
步骤 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 := 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP