github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/collection/listx/stack.go (about)

     1  //nolint:dupl
     2  package listx
     3  
     4  // Stack implements a Last In First Out data structure built upon
     5  // a doubly-linked list.
     6  // The zero value for Stack is an empty stack ready to use.
     7  // A Stack is not safe for concurrent operations.
     8  //
     9  // In most cases, a simple slice based implementation is a better choice.
    10  type Stack[T any] struct {
    11  	l List[T]
    12  }
    13  
    14  // NewStack creates a new Stack instance.
    15  func NewStack[T any]() *Stack[T] {
    16  	return &Stack[T]{}
    17  }
    18  
    19  // Len returns the size of the Stack.
    20  func (s *Stack[T]) Len() int {
    21  	return s.l.Len()
    22  }
    23  
    24  // Push adds on an item on the top of the Stack in *O(1)* time complexity.
    25  func (s *Stack[T]) Push(item T) {
    26  	s.l.PushFront(item)
    27  }
    28  
    29  // Pop removes and returns the item on the top of the Stack in *O(1)* time complexity.
    30  func (s *Stack[T]) Pop() (item T, ok bool) {
    31  	first := s.l.Front()
    32  	if first != nil {
    33  		item = s.l.Remove(first)
    34  		ok = true
    35  	}
    36  	return
    37  }
    38  
    39  // Peek returns the item on the top of the Stack in *O(1)* time complexity,
    40  // it does not remove the item from the Stack.
    41  func (s *Stack[T]) Peek() (item T, ok bool) {
    42  	first := s.l.Front()
    43  	if first != nil {
    44  		item, ok = first.Value.(T), true
    45  	}
    46  	return
    47  }