這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
由於目前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))}}