How to link different but similar structs in a linked circular list?

40 Views Asked by At

I'm trying to implement Knuth's Algorithm X but I'm having trouble with generating the linked list. My column headers and data points are different types, but similar in build.

type ListObject interface{}

type Data struct {
    L, R, U, D, C *ListObject
}

type Column struct {
    L, R, U, D, C *ListObject
    Size          int
    Name          string
}

and this is the very WIP code, where i encountered the problem:

func CreateLinkedList(sparceMatrix [][]int) Column {
    masterHeader := new(Column)
    currentHeader := masterHeader
    for i, col := range sparceMatrix[0] {
    }
    currentHeader.R = masterHeader

    return masterHeader
}

The bit the compiler dislikes is the currentHeader.R = masterHeader bit.

The variables in the Data struct are adjacent dada structs (Left, Right), but U(p) and D(own) could also be a Column object.

I thought about using a interface for a ListObject struct, as you an see, but the compiler does not like that. Other than that, i haven gotten a good idea to the solution. Worse case scenario, i have to make every struct in the list the same type.

Any advice would be appreciated, new to programming.

1

There are 1 best solutions below

4
Adrian On

First and foremost, pointer to interface (like *ListObject) is practically never what you want. That is the cause of your error cannot use masterHeader (variable of type *Column) as *ListObject value in assignment: *Column does not implement *ListObject (type *ListObject is pointer to interface, not interface). Change every instance of *ListObject to ListObject and everything will go more smoothly.

The other error is cannot use masterHeader (variable of type *Column) as Column value in return statement, which is just as it says; you're creating a *Column (pointer to column), but your function signature says you're returning a Column. Likely you want to change the function signature to return *Column here.