好消息,从 Go 1.18 开始,Go 现在支持泛型。

按照问题中的示例,这里是一个使用泛型的简化 LinkedList。您可以在此处的操场上修改它。

package main


import "fmt"


type MyNode[T any] struct {

    next  *MyNode[T]

    value T

}


type MyLinkedList[T any] struct {

    head *MyNode[T]

    tail *MyNode[T]

}


func (list *MyLinkedList[T]) Add(t T) *MyLinkedList[T] {

    // create node

    node := &MyNode[T]{nil, t}

    // if first node in list

    if list.head == nil {

        list.head = node

        list.tail = node

    } else {

        list.tail.next = node

        list.tail = list.tail.next

    }


    return list

}


func (list *MyLinkedList[T]) AddBeforeHead(t T) *MyLinkedList[T] {

    node := &MyNode[T]{nil, t}

    if list.head != nil {

        node.next = list.head

        list.head = node

    } else {

        // make head

        list.head = node

        list.tail = node

    }


    return list

}


// display the list

func DisplayList[T any](list *MyLinkedList[T]) string {

    var out string = ""

    iter := list.head

    for iter != nil {

        out += fmt.Sprintf("%v -> ", iter.value)

        iter = iter.next

    }

    return out

}


func (list *MyLinkedList[T]) Display() string {

    return DisplayList(list)

}


// for printing node value

// you could also implement Stringer

// but this is besides the point, you can ignore

func (node *MyNode[T]) String() string {

    return fmt.Sprintf("<MyNode: %v>", node.value)

}


// helper func: create list from array

func CreateLinkedList[T any](arr []T) *MyLinkedList[T] {

    list := &MyLinkedList[T]{}


    for _, v := range arr {

        list.Add(v)

    }


    return list

}


func main() {

    // create a list from array of integers

    intArr := []int{10, 20, 30, 40, 50, 60}

    list1 := CreateLinkedList(intArr)

    // create a list from array of strings

    strArr := []string{"foo", "bar", "baz", "faz"}

    list2 := CreateLinkedList(strArr)


    // test inserting at the beginning

    list2.AddBeforeHead("hello")


    fmt.Println(list1.Display())

    fmt.Println(list2.Display())

}