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
| #include <iostream>
#include <vector>
class MyStack {
public:
MyStack() {
maxSize = 100;
stackArray.resize(maxSize);
top = -1;
}
void push(int value) {
if (top < maxSize - 1) {
stackArray[++top] = value;
} else {
throw std::runtime_error("Stack is full.");
}
}
int pop() {
if (!isEmpty()) {
return stackArray[top--];
} else {
throw std::runtime_error("Stack is empty.");
}
}
int peek() {
if (!isEmpty()) {
return stackArray[top];
} else {
throw std::runtime_error("Stack is empty.");
}
}
bool isEmpty() {
return top == -1;
}
int size() {
return top + 1;
}
private:
std::vector<int> stackArray;
int maxSize;
int top;
};
int main() {
MyStack intStack;
intStack.push(1);
intStack.push(2);
intStack.push(3);
int topElement = intStack.pop();
bool isEmpty = intStack.isEmpty();
int stackSize = intStack.size();
std::cout << "Top element: " << topElement << std::endl;
std::cout << "Stack is empty: " << (isEmpty ? "true" : "false") << std::endl;
std::cout << "Stack size: " << stackSize << std::endl;
return 0;
}
|