You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
868 B
56 lines
868 B
8 months ago
|
package common
|
||
|
|
||
|
type Stack[T any] struct {
|
||
|
data []*T
|
||
|
}
|
||
|
|
||
|
func NewStack[T any](size int) *Stack[T] {
|
||
|
stack := Stack[T]{}
|
||
|
if size != 0 {
|
||
|
stack.data = make([]*T, 0, size)
|
||
|
} else {
|
||
|
stack.data = make([]*T, 0, 16)
|
||
|
}
|
||
|
|
||
|
return &stack
|
||
|
}
|
||
|
|
||
|
func (s *Stack[T]) Push(element *T) *Stack[T] {
|
||
|
s.data = append(s.data, element)
|
||
|
return s
|
||
|
}
|
||
|
|
||
|
func (s *Stack[T]) Pop() *T {
|
||
|
if s.Size() == 0 {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
element := s.Top()
|
||
|
s.data = s.data[:len(s.data)-1]
|
||
|
return element
|
||
|
}
|
||
|
|
||
|
func (s *Stack[T]) Top() *T {
|
||
|
if s.Size() == 0 {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
return s.data[len(s.data)-1]
|
||
|
}
|
||
|
|
||
|
func (s *Stack[T]) Bottom() *T {
|
||
|
if s.Size() == 0 {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
return s.data[0]
|
||
|
}
|
||
|
|
||
|
func (s *Stack[T]) Size() int {
|
||
|
return len(s.data)
|
||
|
}
|
||
|
|
||
|
func (s *Stack[T]) Empty() bool {
|
||
|
return s.Size() == 0
|
||
|
}
|