pq refactoring
follow container/heap example from std doc.
Vladimir Bauer
2 years ago
| 19 | 19 | } |
| 20 | 20 | |
| 21 | 21 | func (pq *priorityQueue) Push(x interface{}) { |
| 22 | s := *pq | |
| 22 | n := len(*pq) | |
| 23 | 23 | bar := x.(*Bar) |
| 24 | bar.index = len(s) | |
| 25 | s = append(s, bar) | |
| 26 | *pq = s | |
| 24 | bar.index = n | |
| 25 | *pq = append(*pq, bar) | |
| 27 | 26 | } |
| 28 | 27 | |
| 29 | 28 | func (pq *priorityQueue) Pop() interface{} { |
| 30 | s := *pq | |
| 31 | *pq = s[0 : len(s)-1] | |
| 32 | bar := s[len(s)-1] | |
| 29 | old := *pq | |
| 30 | n := len(old) | |
| 31 | bar := old[n-1] | |
| 32 | old[n-1] = nil // avoid memory leak | |
| 33 | 33 | bar.index = -1 // for safety |
| 34 | *pq = old[:n-1] | |
| 34 | 35 | return bar |
| 35 | 36 | } |