當索引位於第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