Hello! I’m trying to build an app based on Aho/Ullmann’s linked list model from “Foundation of Computer Science in C”, they does use a struct with a pointer type to it like this
type Node struct {
label string
next *Node
}
type List *Node
So, while the operation to insert new nodes does the job, I’m experiencing some technical difficulties by deleting Node from the list. I can not find a solution to my problem: the program fails with panic when the delete method reaches the end of the linked list without find the data element. Here is the code
func (l *Node) delete(data string) {
if l != nil {
if l.label == data {
*l = *l.next
} else {
l = l.next
l.delete(data)
}
}
Try this small example to figure out how to insert and delete from a simple linked list. The code is C like but also Go idiomatic. I put comments in some points, pay attention of them.
LE: Working with data structures and algorithms often need drawing the structures and pointers on a piece of paper. Try this to better understand the pointers and their movement.
Hi George, I’m trying to solve the problem with recursion because I’m carrying out the exercises from Aho/Ullman’s book “Foundation of Computer Science in C”, chapter six, “List data model”. Then I’d like to use methods instead of functions. So here the last version of delete method
func (l *List) delete(data string, prev *Node) {
if l != nil {
// It's Head
if prev == nil && l.label == data
// remove the head: I don't know how to accomplish this
return
}
// It's Last element
if l.next == nil && l.label == data {
// No problem with this block of code
prev.prossimo = nil
return
}
// It's Tail
if l.next == data {
// No problem with this block of code
*l = *l.next
return
}
p := l
l = l.next
l.delete(data, p)
}
}
I added a second parameter, the pointer to the previous node, but now I can not erase the head when the list contains only one element.
Singly linked list. I have to solve the same problem as this user has but the algorithm must be recursive and the method’s parameter is the element to delete not a node to it.