Golang LinkedList remove first element

Issue

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?

Solution

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?

Answered By – icza

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.