github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xcontainer/priority_queue/string.go (about)

     1  package priority_queue
     2  
     3  import (
     4  	"container/heap"
     5  )
     6  
     7  type maxStringHeap []string
     8  
     9  func (s maxStringHeap) Len() int {
    10  	return len(s)
    11  }
    12  
    13  func (s maxStringHeap) Less(i, j int) bool {
    14  	return s[i] > s[j]
    15  }
    16  
    17  func (s maxStringHeap) Swap(i, j int) {
    18  	s[i], s[j] = s[j], s[i]
    19  }
    20  
    21  func (s *maxStringHeap) Push(x interface{}) {
    22  	*s = append(*s, x.(string))
    23  }
    24  
    25  func (s *maxStringHeap) Pop() interface{} {
    26  	if len(*s) == 0 {
    27  		return nil
    28  	}
    29  	q := (*s)[len(*s)-1]
    30  	*s = (*s)[:len(*s)-1]
    31  	return q
    32  }
    33  
    34  type minStringHeap []string
    35  
    36  func (s minStringHeap) Len() int {
    37  	return len(s)
    38  }
    39  
    40  func (s minStringHeap) Less(i, j int) bool {
    41  	return s[i] < s[j]
    42  }
    43  
    44  func (s minStringHeap) Swap(i, j int) {
    45  	s[i], s[j] = s[j], s[i]
    46  }
    47  
    48  func (s *minStringHeap) Push(x interface{}) {
    49  	*s = append(*s, x.(string))
    50  }
    51  
    52  func (s *minStringHeap) Pop() interface{} {
    53  	if len(*s) == 0 {
    54  		return nil
    55  	}
    56  	q := (*s)[len(*s)-1]
    57  	*s = (*s)[:len(*s)-1]
    58  	return q
    59  }
    60  
    61  func NewStringPriorityQueue(max bool, items ...string) *PriorityQueue {
    62  	var h heap.Interface
    63  	if max {
    64  		t := maxStringHeap(items)
    65  		h = &t
    66  	} else {
    67  		t := minStringHeap(items)
    68  		h = &t
    69  	}
    70  	return NewPriorityQueue(h)
    71  }