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