-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.go
49 lines (39 loc) · 1022 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
44
45
46
47
48
49
// This file contains the implementation of the stack the CPU uses.
//
// Note that the stack is used for storing integers only.
package cpu
import "errors"
// Stack holds return-addresses when the `call` operation is being
// completed. It can also be used for storing ints.
type Stack struct {
// The entries on our stack
entries []int
}
//
// Stack functions
//
// NewStack creates a new stack object.
func NewStack() *Stack {
return &Stack{}
}
// Empty returns true if the stack is empty.
func (s *Stack) Empty() bool {
return (len(s.entries) <= 0)
}
// Size retrieves the length of the stack.
func (s *Stack) Size() int {
return (len(s.entries))
}
// Push adds a value to the stack.
func (s *Stack) Push(value int) {
s.entries = append(s.entries, value)
}
// Pop removes a value from the stack.
func (s *Stack) Pop() (int, error) {
if s.Empty() {
return 0, errors.New("Pop from an empty stack")
}
result := s.entries[0]
s.entries = append(s.entries[:0], s.entries[1:]...)
return result, nil
}