Golang程序 当索引在链表中超出范围时删除第i个索引节点
例子

解决这个问题的方法
第1步 - 定义一个方法,接受一个链表的头部。
第2步 - 如果 head == nil,返回头部。
第3步 - 当 index == 0 时,则返回 head.next
第4步 - 否则,从头部开始迭代给定的链表。
第5步 - 如果索引i与给定的索引(要删除的)相匹配,那么删除该 Node.next ,中断循环。
第6步 - 返回,在循环结束时。
例子
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 DeleteKthIndexNode(head *Node, index int) *Node{
if head == nil{
return head
}
if index == 0{
head = head.next
return head
}
i := 1
temp := head
for temp != nil{
if i == index{
temp.next = temp.next.next
}
i++
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)
index := 5
head = DeleteKthIndexNode(head, index)
fmt.Printf("After Deletion of %dth index node, Linked List is: ", index)
TraverseLinkedList(head)
}
输出
Input Linked list is: 30 10 40 40
After Deletion of 5th index node, Linked List is: 30 10 40 40
极客教程