Go 语言程序,用于删除链表中第 i 个索引节点,当索引为链表的最后一个索引时。
示例

解决此问题的方法
步骤 1 − 定义一个接受链表头的方法。
步骤 2 − 如果 head == nil,则返回 head。
步骤 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 := 1
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 3th index node, Linked List is: 30 40 40
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP