Golang Standard library container/ring and Container/heap

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

Since Golang currently does not provide a generic mechanism, the generic container implementation is basically similar to C, Golang with interface{} and C is transferred with void *.

The ring package realizes a circular doubly linked list:

Type Ring struct {Next, prev *ring Value interface{}}

Internally exports a value field that a user can manipulate.

The heap package implements binary heap:

Type Interface Interface {sort. Interface Push (x interface{})//Add x as Element len () Pop () interface{}//Remove and return element Len ()-1 .}

Heap. Interface inline sort. Interface, provides a good example of the interface combination, as long as the customer's data type implementation of these five methods, you can insert binary heap, related operations (sorting, priority queue, etc.).

package mainimport  ("Container/heap" "container/ring" "FMT") Func josephus (N, m int)  []int {var res []intring := ring. New (n) ring. Value = 1for i, p := 2, ring. Next ();  p != ring; i, p = i+1, p.next ()  {p.value = i}h  := ring. Prev () For h != h.next ()  {for i := 1; i < m; i++  {h = h.next ()}res = append (Res, h.unlink (1). Value. (int))} Res = append (Res, h.value. ( int)) return res}type intheap []intfunc  (h intheap)  len ()  int            { return len (h)  }func  (h  INTHEAP)  less (i, j int)  bool { return h[i] < h[j] }func   (H&NBSP;INTHEAP)  swap (i, j int) &NBSP;&NBSP;&NBSP;&NBsp;  { h[i], h[j] = h[j], h[i] }func  (h *intHeap)  Push ( x interface{})  {*h = append (*h, x. (int))}func  (h *intheap)  Pop ()   Interface{} {old := *hn := len (old) x := old[n-1]*h = old[0 :  n-1]return x}func main ()  {fmt. Println (Josephus (9, 5)) h := &intheap{10, 3, 9, 7, 2, 88, 31,  67}heap. Init (h) heap. Push (h, 1) For h.len ()  > 0 {fmt. Printf ("%d ",  heap. Pop (h))}}


Related Article

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.