-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathstack_test.go
101 lines (82 loc) · 1.79 KB
/
stack_test.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package ch03
import "testing"
func TestNew(t *testing.T) {
data := 1
item := New(data)
if item.data != data {
t.Errorf("Item data expected to be %d, got %d", data, item.data)
}
}
func TestStackPop(t *testing.T) {
stack := new(Stack[int])
if _, e := stack.Pop(); e == nil {
t.Error("Empty stack should Pop an error")
}
top := New(3)
stack.top = top
top.next = New(2)
top = top.next
top.next = New(1)
values := []int{3, 2, 1}
i := 0
for stack.top != nil {
n, err := stack.Pop()
if err != nil {
t.Errorf("Stack expected to have at least one node")
}
if n != values[i] {
t.Errorf("Stack %d item expected to be %d, got %d", (i + 1), values[i], n)
}
i++
}
}
func TestStackPush(t *testing.T) {
stack := new(Stack[int])
stack.Push(1)
stack.Push(2)
stack.Push(3)
expected := []int{3, 2, 1}
i := 0
for stack.top != nil {
if stack.top.data != expected[i] {
t.Errorf("Stack %d item expected to be %d, got %d", (i + 1), expected[i], stack.top.data)
}
stack.top = stack.top.next
i++
}
}
func TestStackPeek(t *testing.T) {
stack := new(Stack[int])
if _, e := stack.Peek(); e == nil {
t.Error("Empty stack should Peek an error")
}
top := New(3)
stack.top = top
top.next = New(2)
top = top.next
top.next = New(1)
values := []int{3, 2, 1}
i := 0
for stack.top != nil {
n, err := stack.Peek()
if err != nil {
t.Errorf("Stack expected to have at least one node")
}
if n != values[i] {
t.Errorf("Stack %d item expected to be %d, got %d", (i + 1), values[i], n)
}
stack.top = stack.top.next
i++
}
}
func TestStackIsEmpty(t *testing.T) {
stack := new(Stack[int])
if !stack.IsEmpty() {
t.Error("Empty stack should return false")
}
top := New(1)
stack.top = top
if stack.IsEmpty() {
t.Error("Non-empty stack should return true")
}
}