-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
45 lines (36 loc) · 790 Bytes
/
stack.go
File metadata and controls
45 lines (36 loc) · 790 Bytes
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
package stack
// Stack for elements.
type Stack[T any] struct {
top *Element[T]
size int
}
// Element is the single element of the Stack.
type Element[T any] struct {
value T
next *Element[T]
}
// Len returns the stack's length.
func (s *Stack[T]) Len() int {
return s.size
}
// Push a new element onto the stack.
func (s *Stack[T]) Push(value T) {
s.top = &Element[T]{value, s.top}
s.size++
}
// Top returns a value of the top element of the stack.
func (s *Stack[T]) Top() (value T, ok bool) {
if s.size > 0 {
return s.top.value, true
}
return
}
// Pop removes the top element from the stack and returns it's value.
func (s *Stack[T]) Pop() (value T, ok bool) {
if s.size > 0 {
value, s.top = s.top.value, s.top.next
s.size--
return value, true
}
return
}