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)
In this case the value and next pointer of node[8] can be copied to node[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.
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. 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
. 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). So what you try to achieve cannot be done. But you have a function defined for this: Remove(e *Element) interface{}