-
Notifications
You must be signed in to change notification settings - Fork 1
/
stack.go
84 lines (70 loc) · 1.61 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package container
import "fmt"
// Stack is an implementation of Stack
type Stack[T any] struct {
list *List[T] // hide all methods of List
}
// NewStack returns a new Stack object
func NewStack[T any]() *Stack[T] {
l := NewList[T]()
return &Stack[T]{l}
}
// Push a new element to the Stack
func (s *Stack[T]) Push(x T) {
s.list.PushBack(x)
}
// Pop removes the element at the top of the Stack and return the element.
// the Stack must not be empty.
func (s *Stack[T]) Pop() T {
x := s.list.Back()
s.list.Remove(x)
return x.Value
}
// Top returns the element at the top of the Stack.
// the Stack must not be empty.
func (s *Stack[T]) Top() T {
return s.list.Back().Value
}
// Clear all elements from the Stack.
func (s *Stack[T]) Clear() {
s.list.Clear()
}
// Len returns the size of the Stack.
func (s *Stack[T]) Len() int {
return s.list.Len()
}
/////////////////////////////
///////// Testing ///////////
/////////////////////////////
func checkStackSize(s *Stack[int], expect int) {
if s.Len() != expect {
panic(fmt.Sprintf("size check failed, got %d, expect %d", s.Len(), expect))
}
}
func checkStackNum(got, expect int) {
if got != expect {
panic(fmt.Sprintf("answer does not match, got %d, expect %d", got, expect))
}
}
func testStack() {
s := NewStack[int]()
checkStackSize(s, 0)
s.Push(1)
checkStackSize(s, 1)
checkStackNum(s.Top(), 1)
s.Pop()
checkStackSize(s, 0)
s.Push(1)
s.Push(2)
s.Push(3)
checkStackSize(s, 3)
checkStackNum(s.Top(), 3)
s.Pop()
checkStackSize(s, 2)
checkStackNum(s.Top(), 2)
s.Pop()
checkStackSize(s, 1)
checkStackNum(s.Top(), 1)
s.Clear()
checkStackSize(s, 0)
}