Skip to content

Commit

Permalink
pq refactoring
Browse files Browse the repository at this point in the history
follow container/heap example from std doc.
  • Loading branch information
vbauerster committed Aug 28, 2023
1 parent 6b8927e commit e4a12c6
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions priority_queue.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,18 @@ func (pq priorityQueue) Swap(i, j int) {
}

func (pq *priorityQueue) Push(x interface{}) {
s := *pq
n := len(*pq)
bar := x.(*Bar)
bar.index = len(s)
s = append(s, bar)
*pq = s
bar.index = n
*pq = append(*pq, bar)
}

func (pq *priorityQueue) Pop() interface{} {
s := *pq
*pq = s[0 : len(s)-1]
bar := s[len(s)-1]
old := *pq
n := len(old)
bar := old[n-1]
old[n-1] = nil // avoid memory leak
bar.index = -1 // for safety
*pq = old[:n-1]
return bar
}

0 comments on commit e4a12c6

Please sign in to comment.