2

I'm trying to implement LinkedList operation in Golang from scratch. But I found a problem when dealing with removing first element. My approach is using OOP style, but it seems the first element is not removed. This is the code I write,

type LinkedList struct {
    Value int
    next  *LinkedList
}

func (ll *LinkedList) Remove(index int) error {
    pointer := ll
    var pointerPrev *LinkedList = nil
    current := 0

    for current < index {
        pointerPrev = pointer
        pointer = pointer.next
        current++
    }

    if pointer == ll {
        ll = ll.next // this line is problematic
        pointer = nil
    } else {
        if pointer.next == nil {
            pointerPrev.next = nil
        } else {
            pointerPrev.next = pointer.next
            pointer = nil
        }
    }

    return nil
}

Any suggestion how I implement this way of removing without returning new LinkedList pointer?

Dryluigi
  • 35
  • 2
  • 6

1 Answers1

3

Everything is passed as a copy, so you can only change something if a pointer to it is passed, and you modify the pointed value.

So you can't do what you want without having to return the new list head (which you have to assign at the caller).

An alternative could be to pass the address of the head pointer (type of **LinkedList), which is ugly (having to always pass the head pointer's address). You could also add a separate method for removing the first element, something like RemoveFirst(), so you only have to pass to this method only. This RemoveFirst() could return the new head too, which the caller has to assign. This RemoveFirst() could also be a "regular" function instead of a method.

Another alternative is to create a wrapper for the list, which holds a pointer to the head. And you implement methods on the wrapper, not on the node type. And a method of the wrapper could change the field holding the head pointer.

See related: Can the pointer in a struct pointer method be reassigned to another instance?

icza
  • 389,944
  • 63
  • 907
  • 827
  • so how the method is basically works in golang is the **copy** of existing pointer is passed as argument after the func syntax ? so when I reassigned that pointer, I basically just change how the pointer redirect, not the existing object – Dryluigi Mar 12 '22 at 16:02
  • 1
    @Dryluigi Each parameter (the receiver included) acts as a local variable inside the function. When you call a function (or method), the arguments passed are used to initialize these local variables. Changing the parameters (or the receiver) only changes the values of these local variables. The value at the caller is not affected. Changes are carried out by passing pointers and changing the pointed values. Then again, the passed value (pointed) is not changed, only the pointed value. Changing a parameter that is a pointer type only changes the pointer in the local variable (the copy). – icza Mar 12 '22 at 19:24