鏈表的數據結構比較線性數組,優勢是 能夠方便的對任意的位置進行插入和刪除。java
這一特性使得它很適合於應用在排序等場景下,因爲golang目前類庫還不是很完善,在java中能夠很簡單的使用api提供的支持完成對list或者map的排序,在使用go時就沒有那麼幸運了,可能須要本身去實現。golang
下面的例子就是使用go package 中的LinkedList實現的排序的鏈表。api
1.支持固定的長度數組
2.可自定義排序的規則數據結構
3.組合LinkedList功能this
package codeforfun import ( "container/list" ) type SortedLinkedList struct { *list.List Limit int compareFunc func (old, new interface{}) bool } func NewSortedLinkedList(limit int, compare func (old, new interface{}) bool) *SortedLinkedList { return &SortedLinkedList{list.New(), limit, compare} } func (this SortedLinkedList) findInsertPlaceElement(value interface{}) *list.Element { for element := this.Front(); element != nil; element = element.Next() { tempValue := element.Value if this.compareFunc(tempValue, value) { return element } } return nil } func (this SortedLinkedList) PutOnTop(value interface{}) { if this.List.Len() == 0 { this.PushFront(value) return } if this.List.Len() < this.Limit && this.compareFunc(value, this.Back().Value) { this.PushBack(value) return } if this.compareFunc(this.List.Front().Value, value) { this.PushFront(value) } else if this.compareFunc(this.List.Back().Value, value) && this.compareFunc(value, this.Front().Value) { element := this.findInsertPlaceElement(value) if element != nil { this.InsertBefore(value, element) } } if this.Len() > this.Limit { this.Remove(this.Back()) } }
package main import ( "fmt" "codeforfun" ) type WordCount struct { Word string Count int } func compareValue(old, new interface {}) bool { if new.(WordCount).Count > old.(WordCount).Count { return true } return false } func main() { wordCounts := []WordCount{ WordCount{"kate", 87}, WordCount{"herry", 92}, WordCount{"james", 81}} var aSortedLinkedList = codeforfun.NewSortedLinkedList(10, compareValue) for _, wordCount := range wordCounts { aSortedLinkedList.PutOnTop(wordCount) } for element := aSortedLinkedList.List.Front(); element != nil; element = element.Next() { fmt.Println(element.Value.(WordCount)) } }
還能夠訪問我樹莓派上搭的博客地址:spa