github.com/saintwish/kv@v1.0.4/stack/stack.go (about)

     1  package stack
     2  
     3  //last in, first out stack
     4  
     5  import (
     6  
     7  )
     8  
     9  type Stack[V any] struct {
    10  	stack []V
    11  	size int
    12  }
    13  
    14  func New[V any](sz int) *Stack[V] {
    15  	return &Stack[V] {
    16  		//stack: []V{},
    17  		stack: make([]V, 0, sz),
    18  	}
    19  }
    20  
    21  //Pushed value onto the top of the stack and returns index of recently added element
    22  func (s *Stack[V]) Push(val V) (index int) {
    23  	s.stack = append(s.stack, val)
    24  	s.size++
    25  	index = s.size-1
    26  	return
    27  }
    28  
    29  //Returns the index and value of the last element on the stack.
    30  func (s *Stack[V]) Back() (int, V) {
    31  	return s.size-1, s.stack[s.size-1]
    32  }
    33  
    34  //Returns the index and value of the last element on the stack.
    35  func (s *Stack[V]) BackIndex() (int) {
    36  	return s.size-1
    37  }
    38  
    39  //Returns the index of the first element on the stack.
    40  func (s *Stack[V]) Front() (int, V) {
    41  	return 0, s.stack[0]
    42  }
    43  
    44  //Returns the index of the first element on the stack.
    45  func (s *Stack[V]) FrontIndex() (int) {
    46  	return 0
    47  }
    48  
    49  //Remove from the bottom of the stack. Returns index of element that was removed.
    50  func (s *Stack[V]) Pop() (index int, val V) {
    51  	if s.size == 0 {
    52  		index = 0
    53  		return
    54  	}
    55  
    56  	index, val = s.size-1, s.stack[s.size-1]
    57  	s.stack = s.stack[:s.size-1]
    58  	s.size--
    59  	return
    60  }
    61  
    62  //Remove a element by the index on the stack.
    63  func (s *Stack[V]) Remove(index int) {
    64  	s.stack = append(s.stack[:index], s.stack[index+1:]...)
    65  	s.size--
    66  }
    67  
    68  //Moves a element to the back of the stack.
    69  func (s *Stack[V]) MoveToBack(index int) (int) {
    70  	if s.size <= 1 {
    71  		return 0
    72  	}
    73  
    74  	val := s.stack[index]
    75  	s.Remove(index)
    76  	return s.Push(val)
    77  }
    78  
    79  //Clears the entire stack but keep allocated memory
    80  func (s *Stack[V]) Clear() {
    81  	s.stack = s.stack[:0]
    82  }
    83  
    84  func (s *Stack[V]) Stack() []V {
    85  	return s.stack
    86  }