-
Notifications
You must be signed in to change notification settings - Fork 47
/
StackArray.cpp
137 lines (69 loc) · 2.03 KB
/
StackArray.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <iostream>
using namespace std;
/* defining size of stack */
const int MAX = 100;
/* declaring stack */
int stack[MAX];
/*
this top variable plays an important role in stack. This variable tells us whether the stack is empty or full. Also we always insert element at the top and delete element from the top.
*/
int top = -1;
/* It checks whether the stack is empty or not, obviously if top is -1, the stack will be empty. */
bool isEmpty() {
if(top < 0) {
return 1;
}
return 0;
}
/* It checks whether the stack is full or not, obviously if top is MAX - 1, the stack will be full. */
bool isFull() {
if(top >= MAX - 1) {
return 1;
}
return 0;
}
/* function to push an element in the stack. */
int push(int key) {
/*
if top becomes equal to MAX-1, then it means the array is full and we can't insert any element.
isFull() will return true, if stack is full.
*/
if(isFull()) {
cout << "Stack Overflow" << endl;
return 0;
}
/* otherwise, increment top and add key to stack[top], here top works as an index only. */
stack[++top] = key;
cout << "The element is pushed and top points to => " << stack[top] << endl;
return 1;
}
/* function to delete an element in the stack, it returns the deleted element otherwise -1. */
int pop() {
/* if top is -1, it means there is no element to be deleted */
if(isEmpty()) {
cout << "Stack underflow" << endl;
return -1;
}
/* otherwise, delete the element from the top and decrement top. */
int deletedElement = stack[top];
top--;
return deletedElement;
}
/* function through which we can see the element present at the top. */
int peek() {
if(isEmpty()) {
cout << "There is no record in the stack." << endl;
return -1;
}
int peekElement = stack[top];
return peekElement;
}
int main(int argc, char const *argv[]) {
push(10);
push(20);
push(30);
int temp = pop(); // after performing pop, top will point to 20 again.
cout << "Deleted element is: " << temp << endl;
cout << "Top element is: " << peek() << endl;
return 0;
}