golang 排序list_go实现排序的链表

链表的数据结构比较线性数组,优点是 可以方便的对任意的位置进行插入和删除。

这一特性使得它很适合于应用在排序等场景下,由于golang目前类库还不是很完善,在java中可以很简单的使用api提供的支持完成对list或者map的排序,在使用go时就没有那么幸运了,可能需要自己去实现。

下面的例子就是使用go package 中的LinkedList实现的排序的链表。

有几个功能特性:

1.支持固定的长度

2.可自定义排序的规则

3.组合LinkedList功能

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))

}

}

还可以访问我树莓派上搭的博客地址:

有疑问加站长微信联系(非本文作者)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值