Golang 程序删除第 K 个节点之后的节点。

go programmingserver side programmingprogramming

示例

删除 10 个值节点之后的节点。

解决此问题的方法

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

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

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

步骤 4 −如果 temp.value 为 10,则用其下一个节点的下一个值覆盖该节点的下一个值。

步骤 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 DeleteAfterKthNode(head *Node, k int) *Node{
   // 删除第 K 个节点后的内容。
   if head == nil{
      return head
   }
   temp := head
   for temp != nil{
      if temp.value == k{
         temp.next = temp.next.next
      }
      temp = temp.next
   }
   return head
}
func main(){
   head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
   fmt.Printf("输入链表为:")
   TraverseLinkedList(head)
   head = DeleteAfterKthNode(head, 10)
   fmt.Printf("删除第 %d 个值节点后的节点,链表为:", 10)
   TraverseLinkedList(head)
}

输出

输入链表为:30 10 40 40
删除第 10 个值节点后的节点,链表为:30 10 40

相关文章