golang 標準庫 container/ring 及 container/heap

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

由於目前golang 沒有提供泛型機制,所以通用容器實現基本和 c 類似,golang 用 interface{} 做轉接, c 用 void * 轉接。

ring 包實現迴圈雙向鏈表:

type Ring struct   {       next, prev *Ring       Value      interface{} }

內部匯出一個使用者可以操作的Value 欄位。

heap 包實現 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 內嵌 sort.Interface, 提供了介面組合的好例子,只要客戶的資料類型實現這五個方法,即可插入binary heap  中,進行相關操作(排序,優先隊列等)。

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 intHeap) Swap(i, j int)      { 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))}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.