25

Go语言源码阅读(5) - container/ring | 环形链表

 4 years ago
source link: https://www.tuicool.com/articles/jUr6Jba
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

底层双向链表,首位首位相连,形成环。

只有一个结构体,数据成员next和prev私有不对外暴露,Value为interface{}类型,外部可以直接访问。

可通过Next和Prev访问前后的元素。

注意,Next调用时如果next为nil,那么会将当前Ring元素的next和prev设置为自己。其实我觉得直接panic也可以。因为这属于未初始化的Ring。是错误用法。

func (r *Ring) Link(s *Ring) *Ring

连接两个ring。假设链接前:

  r n a
p s b

则链接后:

r s b p n a

即将整个s插入在r之后,r原本的next之前

func (r *Ring) Unlink(n int) *Ring

删除r之后的第n个元素,但是我很奇怪为什么n为0即为什么不能删除自身这个元素

func (r *Ring) Move(n int) *Ring

访问r之后的n个元素,如果n为负数,则是向前访问。

还有几个常规函数:

func New(n int) *Ring

用于创建n个元素的ring。

func (r *Ring) Len() int

用于获取长度,时间复杂度是O(n)。

func (r *Ring) Do(f func(interface{}))

对ring中所有元素执行f操作。

总结:个人感觉Ring的用处不是很大,普通的业务场景直接用数组或者链表就好。如果是高性能场景使用固定大小的环形队列,用ring还不如用数组。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK