Golang 程序更新第 K 个节点后的节点值。

go programmingserver side programmingprogramming

示例

更新 k=10 值节点后的节点

解决此问题的方法

步骤 1 − 定义一个接受链接列表头部的方法。

步骤 2 − 如果 head == nil,则返回头部。

步骤 3 − 迭代给定的链接列表。

步骤 4 −如果 temp.value 为 10,则更新 temp.next.value=data。

步骤 5 − 如果未找到节点值 10,则返回头部而不更新任何节点。

示例

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{
   // 在第 K 个节点之后更新。
   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("输入链表为:")
   TraverseLinkedList(head)
   head = UpdateAfterKthNode(head, 10, 15)
   fmt.Printf("更新第 %d 个值节点后的节点,链表为:", 10)
   TraverseLinkedList(head)
}

输出

输入链表为:30 10 40 40
更新第 10 个值节点后的节点,链表为:30 10 15 40

相关文章