如何实现链表 [英] How to implement a linked list
问题描述
我正在尝试在Go中实现一个排序的链表.而且,我很难想出一种通用的方法来使链表可以与自己相比可以使用的任何类型.由于它是一个有序列表,因此我希望"go编译器"确保可以比较插入到链表中的值.
I'm trying to implement a sorted linked list in Go. And I'm having a hard time coming up with a generic way to make the linked list work with any type that can by compared with itself. Since its a sorted list, I want the 'go compiler' to ensure that the values being inserted into the linked list can be compared.
例如,
import "linkedlist"
type Person struct {
name string
}
func main() {
l := linkedlist.New()
p := Person{"Jay"}
l.insert(p)
}
在上面的示例中,我如何使编译器确保具有"Person"类型的值"p"可以与也具有"Person"类型的另一个值进行比较.我希望编译器在那些插入的值不合适的情况下捕获错误.
In the above example, how do I make the compiler ensure that the value 'p' which has type 'Person' can be compared with another value which also has type 'Person'. I want the compiler to catch the error in those situations where the value being inserted is not an appropriate value.
我可以做这样的事情,
import "linkedlist"
type Element interface {
func IsGreater(v Element{}) bool
}
type Person struct {
name string
age int
}
func (p *Person) IsGreater(p1 interface{}) bool {
if ok, v := p1.(Person); ok && p.age > v.age {
return true
}
return false
}
然后,在链接列表的插入"功能中,我可以使用 IsGreater
函数来确定将元素放置在链接列表中的位置.
And then, within the "insert" function of the linked list I can use the IsGreater
function to decide where to place the Element in the linked list.
我的问题是...
- 是否有更好的方法来做到这一点?比上面的解决方案好很多.
我已经对sort进行了排序,并查看了如何在该包中完成它.这样做的方法是为该类型的切片创建一个新类型,然后通过实现Len,Less和Swap使该新类型满足排序接口.
I've already gone through sort.Sort and seen how its done in that package. The way its done there is to create a new type for a slice of the type and then make that new type fulfill the sort interface by implementing Len, Less and Swap.
就我而言,我在这里也可以做同样的事情.但是当我一次只处理2个相同类型的值时,必须创建一个新的slice类型,然后实现一些功能以满足一个接口.对我来说似乎有点过头了.
I can probably do the same thing here in my case as well. But having to create a new slice type and then implement a few functions to satisfy an interface, when I'll only be dealing with 2 values of the same type at a time.. seems a bit overkill to me.
推荐答案
由于Golang不支持泛型,因此所有容器都应使用interface {}并键入assert,我认为没有更好的解决方案可以满足您的要求.
Because Golang do not support generics, So all of containers should use interface{} and type assert, I think no better solution for your requirement.
这篇关于如何实现链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!