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