Golang 程序在第 K 个节点后插入一个新节点。

go programmingserver side programmingprogramming

示例

在 10 个值节点后添加节点 15。

解决此问题的方法

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

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

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

步骤 4 −如果 temp.value 为 10,则添加节点 15 作为下一个节点。

步骤 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 AddAfterKthNode(head *Node, k , data int) *Node{
   // 在第 K 个节点后插入节点。
   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("输入链接列表是:")
   TraverseLinkedList(head)
   head = AddAfterKthNode(head, 10, 15)
   fmt.Printf("在第 %d 个值节点后添加节点,链表为:", 10)
   TraverseLinkedList(head)
}

输出

输入链表为:30 10 40 40
在第 10 个值节点后添加节点,链表为:30 10 15 40 40

相关文章