-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.go
More file actions
51 lines (42 loc) · 1.12 KB
/
stack.go
File metadata and controls
51 lines (42 loc) · 1.12 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
47
48
49
50
51
package main
import "fmt"
// Stack represents a stack data structure
type Stack[T any] struct {
elements []T
}
// Push adds an element to the top of the stack
func (s *Stack[T]) Push(element T) {
s.elements = append(s.elements, element)
}
// Pop removes and returns the top element of the stack
func (s *Stack[T]) Pop() (T, error) {
if len(s.elements) == 0 {
var zero T
return zero, fmt.Errorf("stack is empty")
}
element := s.elements[len(s.elements)-1]
s.elements = s.elements[:len(s.elements)-1]
return element, nil
}
// Peek returns the top element of the stack without removing it
func (s *Stack[T]) Peek() (T, error) {
if len(s.elements) == 0 {
var zero T
return zero, fmt.Errorf("stack is empty")
}
return s.elements[len(s.elements)-1], nil
}
func (s *Stack[T]) Get(index int) (T, error) {
if len(s.elements) - 1 > index {
var zero T
return zero, fmt.Errorf("Index greater than stack length")
}
return s.elements[index], nil
}
func (s *Stack[T]) Size() int {
return len(s.elements)
}
// IsEmpty checks if the stack is empty
func (s *Stack[T]) IsEmpty() bool {
return len(s.elements) == 0
}