-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path01_stack_array.cpp
More file actions
77 lines (64 loc) · 1.52 KB
/
01_stack_array.cpp
File metadata and controls
77 lines (64 loc) · 1.52 KB
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
#include <iostream>
#include <cstdlib>
#include <string>
#define MAX 100
class Stack {
private:
int data[MAX];
int top;
public:
Stack() {
top = -1;
}
bool isEmpty() const {
return top == -1;
}
bool isFull() const {
return top == MAX - 1;
}
bool push(int value) {
if (isFull())
return false;
data[++top] = value;
return true;
}
bool pop(int &removed) {
if (isEmpty())
return false;
removed = data[top--];
return true;
}
// In C++ you can not use `top` as a name in property.
bool peek(int &value) const {
if (isEmpty())
return false;
value = data[top];
return true;
}
};
int main(int argc, char* argv[]) {
Stack stack;
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg == "pop") {
int removed;
if (stack.pop(removed))
std::cout << "POP " << removed << std::endl;
else
std::cout << "POP FAILED" << std::endl;
}
else {
int value = std::atoi(arg.c_str());
if (stack.push(value))
std::cout << "PUSH " << value << std::endl;
else
std::cout << "PUSH FAILED" << std::endl;
}
}
int topValue;
if (stack.peek(topValue))
std::cout << "TOP " << topValue << std::endl;
else
std::cout << "STACK EMPTY" << std::endl;
return 0;
}