Go Container Pack

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Go Container Pack

container/list- doubly linked list-list

The basic data structure

type Element struct {// 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.Value interface{}}// List represents a doubly linked list.// The zero value for List is an empty list ready to use.type List struct {root Element // sentinel list element, only &root, root.prev, and root.next are usedlen  int     // current list length excluding (this) sentinel element}

The doubly linked list is one of the linked lists, each of which has two pointers in each data node, pointing to direct successors and direct precursors, respectively. So, starting from any node in a doubly linked list, it is easy to access its predecessor and successor nodes. In general, we construct two-way circular linked lists.

For example,

package mainimport ("container/list""fmt")func print(l *list.List) {for e := l.Front(); e != nil; e = e.Next() {fmt.Println(e.Value)}}func main() {l := list.New()l.PushBack(1) //尾插l.PushBack(2)print(l)fmt.Println("=========")l.PushFront(0) //头插print(l)fmt.Println("=========")for e := l.Front(); e != nil; e = e.Next() {if e.Value == 1 {l.InsertAfter(1.1, e)}if e.Value == 2 {l.InsertBefore(1.2, e)}}print(l)fmt.Println("=========")fmt.Println(l.Front().Value) //返回链表的第一个元素fmt.Println("=========")fmt.Println(l.Back().Value) //返回链表的最后一个元素fmt.Println("=========")l.MoveToBack(l.Front())print(l)fmt.Println("=========")for e := l.Back(); e != nil; e = e.Prev() {fmt.Println(e.Value)}}

container/heap-Heap-heap

For a heap data structure, see:

https://my.oschina.net/xinxingegeya/blog/703801

https://my.oschina.net/xinxingegeya/blog/705409

In Golang, a set of methods is defined to describe the operation of the heap. The following interface description,

// Any type that implements heap.Interface may be used as a// min-heap with the following invariants (established after// Init has been called or if the data is empty or sorted):////!h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len()//// Note that Push and Pop in this interface are for package heap's// implementation to call. To add and remove things from the heap,// use heap.Push and heap.Pop.type Interface interface {sort.InterfacePush(x interface{}) // add x as element Len()Pop() interface{}   // remove and return element Len() - 1.}

Heap. Interface combines the sort. Interface interface,

// 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.type Interface interface {// 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, j int) bool// Swap swaps the elements with indexes i and j.Swap(i, j int)}

This means that as long as one type implements these five methods, a heap is defined. As shown below,

Package Mainimport ("Container/heap" "FMT") type Student struct {name Stringscore int}type studentheap []studentfunc (H Stu DENTHEAP) Len () int {return Len (h)}func (H studentheap) Less (i, J int) bool {return H[i].score < H[j].score//min heap//re Turn Stu[i].score > Stu[j].score//Max heap}func (H studentheap) Swap (i, J int) {H[i], h[j] = H[j], H[i]}func (H *studenth EAP) Push (x interface{}) {//Push and POP use pointer receivers because they modify the slice ' s length,//not just its con  Tents.*h = Append (*h, X. (Student))}func (H *studentheap) Pop () interface{} {old: = *hn: = Len (old) x: = Old[n-1]*h = old[0: N-1]return X}func Main () {h: = &studentheap{{name: "Xiaoming", Score:82},{name: "Xiaozhang", Score:88},{name: "Laow Ang ", score:85}}//Initializes a heap. A heap should be initialized before any heap operations are used. The init function is idempotent to the heap (execution is meaningless multiple times) and may be called at any time when the constraint of the heap is broken. The complexity of this function is O (n), where n equals H. Len (). Heap. Init (h)//Insert element X into heap H and maintain the constraint of the heap. The complexity of O (log (n)), where n equals H. Len (). Heap. Push (H, student{name: "Xiaoli", score:66}) for _, Ele: = Range *h {fmt. Printf ("Student name%s,score%d\n ", Ele.name, Ele.score)}for i, ele: = Range *h {if ele.name = =" Xiaozhang "{(*h) [I].score = 60// After modifying the element I, it is more efficient to call this function to fix the heap than to insert a new element after removing the element I. The complexity of O (log (n)), where n equals H. Len (). Heap. Fix (H, i)}}fmt. Println ("==========") for _, Ele: = Range *h {fmt. Printf ("Student name%s,score%d\n", Ele.name, Ele.score)}fmt. Println ("==========") for H.len () > 0 {//delete and return the smallest element in heap h (depending on less function, maximum heap or minimum heap) (does not affect heap de constraint)//Complexity O (log (n)), where n equals H. Len (). The function is equivalent to the Remove (h, 0) Item: = Heap. Pop (h). (Student) fmt. Printf ("Student name%s,score%d\n", Item.name, Item.score)}}

Printing results,

student name xiaoli,score 66student name xiaoming,score 82student name laowang,score 85student name xiaozhang,score 88==========student name xiaozhang,score 60student name xiaoli,score 66student name laowang,score 85student name xiaoming,score 82==========student name xiaozhang,score 60student name xiaoli,score 66student name xiaoming,score 82student name laowang,score 85Process finished with exit code 0

container/ring-Ring-ring

The data structure of the ring,

// 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.//type Ring struct {next, prev *RingValue      interface{} // for use by client; untouched by this library}

Like the structure of a two-way circular list, a doubly linked list, and a two-way circular list,

The following code example

package mainimport ("container/ring""fmt")func main() {ring1 := ring.New(3)for i := 1; i <= 3; i++ {ring1.Value = iring1 = ring1.Next()}ring2 := ring.New(3)for i := 4; i <= 6; i++ {ring2.Value = iring2 = ring2.Next()}r := ring1.Link(ring2)fmt.Printf("ring length = %d\n", r.Len())r.Do(func(p interface{}) {fmt.Print(p.(int))fmt.Print(",")})fmt.Println()fmt.Printf("current ring is %v\n", r.Value)fmt.Printf("next ring is %v\n", r.Next().Value)fmt.Printf("prev ring is %v\n", r.Prev().Value)// ring 的遍历for p := r.Next(); p != r; p = p.Next() {fmt.Print(p.Value.(int))fmt.Print(",")}}

=======end=======

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.