-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpp-data-structures-stack-using-array.cpp
115 lines (93 loc) · 1.53 KB
/
cpp-data-structures-stack-using-array.cpp
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <iostream>
using namespace std;
class Stack {
private:
int size;
int top;
int* S; // array for storing elements in the stack
public:
Stack(int size);
~Stack();
void Display();
void push(int x);
int pop();
int peek(int index);
int isFull();
int isEmpty();
int stackTop();
};
Stack::Stack(int size)
{
this->size = size;
top = -1;
S = new int[size];
}
Stack::~Stack() {
delete S;
}
void Stack::Display() {
int i;
for (i = top; i >= 0; i--)
cout << S[i] << " | ";
cout << endl;
}
void Stack::push(int x) {
if (isFull()) {
cout << "stack overflow" << endl;
} else {
top++;
S[top] = x;
}
}
int Stack::pop() {
int x = -1;
if (isEmpty()) {
cout << "stack underflow" << endl;
}else {
x = S[top];
top--;
}
return x;
}
int Stack::peek(int index) {
int x = -1;
if (top - index + 1 < 0) {
cout << "invalid index" <<endl;
} else {
x = S[top - index + 1];
}
return x;
}
int Stack::isFull() {
if (top == size - 1) {
return 1;
} return 0;
}
int Stack::isEmpty() {
if (top == -1) {
return 1;
}
return 0;
}
int Stack::stackTop() {
if (!isEmpty())
return S[top];
return -1;
}
int main() {
Stack st(5);
st.push(10);
st.push(20);
st.push(30);
st.push(40);
st.push(50);
cout << "Stack: ";
st.Display();
cout << "Peek at 3rd: " << st.peek(3) << endl;
cout << "Peek at 4th: " << st.peek(4) << endl;
cout << "Peek at 2nd: " << st.peek(2) << endl;
cout << "Top element: " << st.stackTop() << endl;
st.pop();
cout << "Stack empty: " << st.isEmpty() << endl;
return 0;
}