【发布时间】:2025-11-26 21:15:02
【问题描述】:
我正在用 Go 实现 Linked List 数据结构。
这个方法应该按照给定的索引插入节点。
但是,这只有在给定索引号 0 时才能正常工作。
我一直在阅读和绘制以找出错误,但我找不到它。
如果有人能提供见解或方法来找出这个错误,我将不胜感激。
您的“insertAt()”逻辑是什么样的?
- 如果给定索引无效,则打印错误消息并完成执行[按预期工作]
- 如果给定索引为 0,则将该节点作为链表的头节点推送 [按预期工作]
- 向链表中给定的索引号插入一个新节点。 [没有按预期工作]
下面是(3)的逻辑,它不能正常工作。
->如果给定的索引有效且大于 0,
->迭代链表,直到迭代达到(给定索引 - 1)的索引
->将新节点指向给定索引中的节点,
-> 使前一个节点指向新节点。
func main() {
fmt.Println("Hello, world.")
ll := &LinkedList{
head: nil,
tail: nil,
length: 1,
}
ll.push(11)
ll.push(12)
ll.insertAt(1, 50)
var testNode = ll.head
for testNode != nil { // This prints,
fmt.Println(testNode) // &{12 0xc000010200} &{11 <nil>}
testNode = testNode.next // But it should be
} // &{12 0xc000010200} &{50 memoryaddress} &{11 <nil>}
}
// Node is an object holding its value and the memory address of next node
type Node struct {
value int
next *Node
}
// LinkedList is a list of Node
type LinkedList struct {
head *Node
tail *Node
length int
}
// Insert node at a given index
func (ll *LinkedList) insertAt(index, data int) {
if index < 0 || index > ll.length {
fmt.Println("invalid index")
} else if index == 0 {
newNode := &Node{
value: data,
next: ll.head,
}
ll.head = newNode
ll.length++
} else {
newNode := &Node{
value: data,
next: nil,
}
counter := 0
currentNode := ll.head
var previousNode Node
// we want to stop iteration at (index - 1)th position
for counter < index {
previousNode := currentNode
currentNode = previousNode.next
counter++
}
newNode.next = currentNode
previousNode.next = newNode
ll.length++
}
}
【问题讨论】:
标签: go data-structures linked-list