-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstack.go
43 lines (38 loc) · 821 Bytes
/
stack.go
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
package immutable
// Stack implements a last in, first out container.
//
// Nil and the zero value for Stack are both empty stacks.
type Stack[T any] struct {
top T
bottom *Stack[T]
}
// Empty returns true if the stack is empty.
//
// Complexity: O(1) worst-case
func (s *Stack[T]) Empty() bool {
return s == nil || s.bottom == nil
}
// Peek returns the top item on the stack.
//
// Complexity: O(1) worst-case
func (s *Stack[T]) Peek() T {
return s.top
}
// Pop removes the top item from the stack.
//
// Complexity: O(1) worst-case
func (s *Stack[T]) Pop() *Stack[T] {
return s.bottom
}
// Push places an item onto the top of the stack.
//
// Complexity: O(1) worst-case
func (s *Stack[T]) Push(value T) *Stack[T] {
if s == nil {
s = &Stack[T]{}
}
return &Stack[T]{
top: value,
bottom: s,
}
}