Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang StringHeapSet
package main
import "container/heap"
type StringHeapSet struct {
heap stringHeapData
}
func (h *StringHeapSet) Push(v string) {
heap.Push(&h.heap, v)
}
func (h *StringHeapSet) Peek() string {
if h.Len() == 0 {
panic("heap is empty")
}
return h.heap.slice[0]
}
func (h *StringHeapSet) Pop() string {
val, ok := heap.Pop(&h.heap).(string)
if !ok {
panic("invalid type in our heap - this shouldn't ever happen")
}
return val
}
func (h *StringHeapSet) Len() int {
return h.heap.Len()
}
type stringHeapData struct {
slice []string
}
func (h stringHeapData) Len() int {
return len(h.slice)
}
func (h stringHeapData) Less(i, j int) bool {
return h.slice[i] < h.slice[j]
}
func (h stringHeapData) Swap(i, j int) {
h.slice[i], h.slice[j] = h.slice[j], h.slice[i]
}
func (h *stringHeapData) Push(x interface{}) {
h.slice = append(h.slice, x.(string))
}
func (h *stringHeapData) Pop() interface{} {
n := len(h.slice)
ret := h.slice[n-1]
h.slice = h.slice[0 : n-1]
return ret
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment