Go 语言程序在 Kth 节点后插入一个新节点(K 不在链表中)
示例

在 50(K 不在链表中)值节点后追加节点 15。
解决此问题的步骤
步骤 1 − 定义一个接受链表头的方法。
步骤 2 − 如果 head == nil,则返回 head。
步骤 3 − 迭代给定的链表。
步骤 4 − 如果未找到节点值 50,则在不添加任何节点的情况下返回 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 AddAfterKthNode(head *Node, k , data int) *Node{
// Insert after Kth node(K is not in the linked list).
if head == nil{
return head
}
temp := head
for temp != nil{
if temp.value == k{
newNode := NewNode(data, nil)
newNode.next = temp.next
temp.next = newNode
break
}
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 = AddAfterKthNode(head, 50, 15)
fmt.Printf("Adding node after %dth value node, Linked List is: ", 50)
TraverseLinkedList(head)
}输出
Input Linked list is: 30 10 40 40 Adding 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