-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementStackByArray.cpp
More file actions
65 lines (57 loc) · 1.24 KB
/
Copy pathImplementStackByArray.cpp
File metadata and controls
65 lines (57 loc) · 1.24 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
#include <iostream>
using namespace std;
class MyStack {
public:
int* arr;
int top;
int capacity;
MyStack(int size) {
capacity = size;
arr = new int[capacity];
top = -1;
}
// Push element x onto stack
void push(int x) {
if (top == capacity - 1) {
cout << "Stack Overflow\n";
return;
}
top++;
arr[top] = x;
}
// Remove top element from stack
int pop() {
if (top == -1) {
cout << "Stack Underflow\n";
return -1;
}
int poppedElement = arr[top];
top--;
return poppedElement;
}
// Get the top element
int peek() {
if (top == -1) {
cout << "Stack is Empty\n";
return -1;
}
return arr[top];
}
// Check if stack is empty
bool isEmpty() {
return top == -1;
}
// Destructor to free memory
~MyStack() {
delete[] arr;
}
};
int main() {
MyStack s(5);
s.push(10);
s.push(20);
cout << "Top element is: " << s.peek() << "\n";
cout << "Popped element is: " << s.pop() << "\n";
cout << "Is stack empty? " << (s.isEmpty() ? "Yes" : "No") << "\n";
return 0;
}