Golang程序 删除第K个节点之后的节点(K不在链接列表中)
例子

删除第50个(K不在链接列表中)数值节点之后的节点。
解决这个问题的方法
第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 DeleteAfterKthNode(head *Node, k int) *Node{
// Delete 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 = 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, 50)
fmt.Printf("Delete node after %dth value node, Linked List is: ", 50)
TraverseLinkedList(head)
}
输出
Input Linked list is: 30 10 40 40
Delete node after 50th value node, Linked List is: 30 10 40 40
极客教程