-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.go
56 lines (48 loc) · 1 KB
/
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
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"bytes"
)
// Stack is a stack of matrices
type Stack struct {
stack []*Matrix
}
// NewStack returns a new stack
func NewStack() *Stack {
return &Stack{
stack: make([]*Matrix, 0, 10),
}
}
// Pop returns and removes the top matrix in the stack
func (s *Stack) Pop() *Matrix {
if s.IsEmpty() {
return nil
}
length := len(s.stack)
ret := s.stack[length-1]
s.stack = s.stack[:length-1]
return ret
}
// Push pushes a new matrix onto the stack
func (s *Stack) Push(m *Matrix) {
s.stack = append(s.stack, m)
}
// Peek returns the top matrix in the stack
func (s *Stack) Peek() *Matrix {
if s.IsEmpty() {
return nil
}
length := len(s.stack)
return s.stack[length-1]
}
// IsEmpty returns true if the stack is empty, false otherwise
func (s *Stack) IsEmpty() bool {
return len(s.stack) == 0
}
func (s *Stack) String() string {
var buffer bytes.Buffer
length := len(s.stack)
for i := length - 1; i >= 0; i-- {
buffer.WriteString(s.stack[i].String())
}
return buffer.String()
}