简体   繁体   English

如何更新转到列表中的下一个指针?

[英]How to update the next pointer in place in go list?

I have a node pointer from the list. 我有一个列表中的节点指针。 I want update the value and next pointer with the next node in the list. 我想用列表中的下一个节点更新值和下一个指针。 This is nothing but deletion in place given access to only that pointer. 这仅是删除,仅允许访问该指针。

For example 3 -> 5 -> 8 -> 9 Node to be deleted : 5 (given access to only 5. Assuming previous node is not known) 例如3-> 5-> 8-> 9要删除的节点:5(只允许访问5。假定先前的节点未知)

In this case the value and next pointer of node[8] can be copied to node[5]. 在这种情况下,可以将节点[8]的值和下一个指针复制到节点[5]。 I have the following code. 我有以下代码。 It is not removing the element. 它没有删除元素。 If I try to access the next pointer using 'next' keyword it is throwing error. 如果我尝试使用“ next”关键字访问下一个指针,则会引发错误。

package main
import (
    "container/list"
    "fmt"
)

func main() {

    l := list.New()
    l.PushFront(4)
    l.PushFront(5)
    e4 := l.PushFront(7)
    l.PushFront(6)
    l.PushBack(9)
    res := deleteNode(e4)
    fmt.Println(res)

    for e:=l.Front(); e!=nil;e=e.Next() {
        fmt.Println(e.Value)
    }

}
//ERROR
func deleteNode(node *list.Element) bool {

    if node == nil || node.Next() == nil {
        return false
    }
    var nextNode *list.Element 
    nextNode := node.next.(*list.Element)
    node.Value = node.Next().Value.(int)
    nextNode = nextNode.next.(*Element)
    return true
}

Could anyone help me with this? 有人可以帮我吗?

The (first) error you get is: 您得到的(第一个)错误是:

no new variables on left side of :=

Because nextNode already exists. 因为nextNode已经存在。 The problem is with these 2 lines: 问题在于这两行:

var nextNode *list.Element 
nextNode := node.next.(*list.Element)

In the first line you create the variable nextNode . 在第一行中,创建变量nextNode In the second line you use the short assignment := which creates a new variable (specified by the left side) and assigns to it the value on the right side. 在第二行中,您使用了短赋值:= ,它创建了一个新变量(由左侧指定),并在右侧分配了值。 Just leave out the first line, you only need one of those: 只需省略第一行,您只需要其中之一:

nextNode := node.Next()

Moreover you cannot read or change the next pointer of a node because the next pointer is not exported in the Element struct (it starts with lowercased letter). 此外,您不能读取或更改节点的next指针,因为next指针不会在Element结构中导出(它以小写字母开头)。 So what you try to achieve cannot be done. 因此,您尝试实现的目标无法完成。 But you have a function defined for this: Remove(e *Element) interface{} 但是您为此定义了一个函数: Remove(e *Element) interface{}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM