-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray_stack.go
58 lines (46 loc) · 1.06 KB
/
array_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
57
58
package stack
import (
"strings"
arr "go-algorithms/data_structures/array"
)
// ArrayStack 使用动态数组实现栈
//
// 使用数组末尾作为栈顶
// 示意图为 Bottom [..., 1, 3, 5 ] Top
type ArrayStack struct {
items *arr.DynamicArray
}
// NewArrayStack 返回一个新的动态数组实现的空栈
func NewArrayStack() *ArrayStack {
return &ArrayStack{
items: arr.New(),
}
}
func (s *ArrayStack) Push(data interface{}) {
s.items.Append(data)
}
func (s *ArrayStack) Pop() interface{} {
if s.IsEmpty() {
panic("Can't pop from empty stack.")
}
return s.items.Remove(s.items.Size() - 1)
}
func (s *ArrayStack) Peek() interface{} {
if s.IsEmpty() {
panic("Can't peek from empty stack.")
}
return s.items.Get(s.items.Size() - 1)
}
func (s *ArrayStack) IsEmpty() bool {
return s.items.IsEmpty()
}
func (s *ArrayStack) Size() int {
return s.items.Size()
}
func (s *ArrayStack) String() string {
var builder strings.Builder
builder.WriteString("Bottom ")
builder.WriteString(s.items.String())
builder.WriteString(" Top")
return builder.String()
}