// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
typeInterfaceinterface{// Len is the number of elements in the collection.
Len()int// Less reports whether the element with
// index i should sort before the element with index j.
Less(i,jint)bool// Swap swaps the elements with indexes i and j.
Swap(i,jint)}
// List represents a doubly linked list.
// The zero value for List is an empty list ready to use.
typeListstruct{rootElement// sentinel list element, only &root, root.prev, and root.next are used
lenint// current list length excluding (this) sentinel element
}
其中Element结构体定义如下
next表示下一个元素,使用Next()可以获取到
prev表示上一个元素,使用Prev()可以获取到
list表示元素属于哪个链表
Value表示元素的值,interface{}在Go语言中表示任意类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Element is an element of a linked list.
typeElementstruct{// Next and previous pointers in the doubly-linked list of elements.
// To simplify the implementation, internally a list l is implemented
// as a ring, such that &l.root is both the next element of the last
// list element (l.Back()) and the previous element of the first list
// element (l.Front()).
next,prev*Element// The list to which this element belongs.
list*List// The value stored with this element.
Valueinterface{}}
graph LR
A -->B
B -->C
C -->D
D -->E
E -->D
A -->E
E -->A
D -->C
C -->B
B -->A
双向循环链表和双向链表区别
双向循环链表没有严格意义上的头元素和尾元素
没有元素的前连接和后连接为nil
一个长度为n的双向循环链表,通过某个元素向某个方向移动,在查找最多n-1次后一定会找到另一个元素
Go语言中的双向循环链表
在container/ring包下结构体Ring源码如下
官方明确说明了Ring是循环链表的元素,又是环形链表.
实际使用时Ring遍历就是环形链表第一个元素
1
2
3
4
5
6
7
8
9
10
// A Ring is an element of a circular list, or ring.
// Rings do not have a beginning or end; a pointer to any ring element
// serves as reference to the entire ring. Empty rings are represented
// as nil Ring pointers. The zero value for a Ring is a one-element
// ring with a nil Value.
//
typeRingstruct{next,prev*RingValueinterface{}// for use by client; untouched by this library
}