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

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

例子

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

删除第10个节点后的节点。

解决这个问题的方法

第1步 - 定义一个方法,接受一个链表的头部。

第2步 - 如果head == nil,返回head。

第3步 - 遍历给定的链表。

第4步 – 如果 temp.value 是10,那么用它的下一个节点的下一个值覆盖该节点的下一个值。

第5步 - 如果没有找到节点值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 DeleteAfterKthNode(head *Node, k int) *Node{
   // Delete after Kth node.
   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("Input Linked list is: ")
   TraverseLinkedList(head)
   head = DeleteAfterKthNode(head, 10)
   fmt.Printf("Delete node after %dth value node, Linked List is: ", 10)
   TraverseLinkedList(head)
}

输出

Input Linked list is: 30 10 40 40
Delete node after 10th value node, Linked List is: 30 10 40

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程