发布日期 :2019-05-16 07:05:50 UTC
访问量: 10 次浏览

解决这个问题的方法
第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 := 0
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 0th index node, Linked List is: 15 10 40 40