【问题标题】:How to insert node at given index of a linked list如何在链表的给定索引处插入节点
【发布时间】:2025-11-26 21:15:02
【问题描述】:

我正在用 Go 实现 Linked List 数据结构。

这个方法应该按照给定的索引插入节点。

但是,这只有在给定索引号 0 时才能正常工作。

我一直在阅读和绘制以找出错误,但我找不到它。

如果有人能提供见解或方法来找出这个错误,我将不胜感激。

您的“insertAt()”逻辑是什么样的?

  1. 如果给定索引无效,则打印错误消息并完成执行[按预期工作]
  2. 如果给定索引为 0,则将该节点作为链表的头节点推送 [按预期工作]
  3. 向链表中给定的索引号插入一个新节点。 [没有按预期工作]

下面是(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


    【解决方案1】:

    实现有两个错误:

    首先:previousNode 必须是 var previousNode *Node 而不是 Node

    第二:您在 for 循环中重新声明 previousNode。因此,您永远不会真正为前一个节点设置指针。使用previousNode=currentNode,而不是:=

    【讨论】:

    • 谢谢!之所以var previousNode *Node 应该是pointer of type Node 而不是the type Node,是因为我们在链接列表中处理pointer to Node。我说的对吗?
    • 它是一个指针,因为您要更改列表中的节点,而不是它的副本。
    • for 循环工作正常,previousNode(它是一个 *Node)和 currentNode 向前移动。当循环终止时,循环中设置的previousNode被遗忘,你在previousNode中设置了next字段,这是一个未初始化的Node(不是指针)。
    • 不,你在循环中重新声明了previousNode。它们是两个不同的变量。
    • 可以在不同的范围内重新定义同名变量:golang.org/ref/spec#Short_variable_declarations