-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
46 lines (38 loc) · 1.2 KB
/
Copy pathstack.go
File metadata and controls
46 lines (38 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package gds
// Stack is a LIFO (last-in, first-out) collection.
// It is not safe for concurrent use.
type Stack[T any] struct {
items []T
}
// NewStack returns an empty Stack.
func NewStack[T any]() *Stack[T] { return &Stack[T]{} }
// Push adds one or more items onto the top of the stack.
func (s *Stack[T]) Push(items ...T) {
s.items = append(s.items, items...)
}
// Pop removes and returns the top element.
// Returns the zero value and false if the stack is empty.
func (s *Stack[T]) Pop() (T, bool) {
if len(s.items) == 0 {
var zero T
return zero, false
}
top := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return top, true
}
// Peek returns the top element without removing it.
// Returns the zero value and false if the stack is empty.
func (s *Stack[T]) Peek() (T, bool) {
if len(s.items) == 0 {
var zero T
return zero, false
}
return s.items[len(s.items)-1], true
}
// Len returns the number of elements in the stack.
func (s *Stack[T]) Len() int { return len(s.items) }
// IsEmpty reports whether the stack has no elements.
func (s *Stack[T]) IsEmpty() bool { return len(s.items) == 0 }
// Clear removes all elements from the stack.
func (s *Stack[T]) Clear() { s.items = nil }