Go语言程序:更新第K个节点之后的节点值(当K不在链表中)
示例

更新k=50值节点后的节点
解决这个问题的方法
步骤1 − 定义一个接受链表头的方法。
步骤2 − 如果head == nil,则返回head。
步骤3 − 迭代给定的链表。
步骤4 − 如果找不到节点值10,则返回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 UpdateAfterKthNode(head *Node, k, data int) *Node{
// Update after Kth node(K is not in the linked list).
if head == nil{
return head
}
temp := head
for temp != nil{
if temp.value == k{
temp.next.value = data
}
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)
head = UpdateAfterKthNode(head, 50, 15)
fmt.Printf("Update node after %dth value node, Linked List is: ", 50)
TraverseLinkedList(head)
}输出
Input Linked list is: 30 10 40 40 Update node after 50th value node, Linked List is: 30 10 40 40
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP