Stack Using Array
#include<iostream>
using namespace std;
class Stack{
int *arr;
int top;
int size;
public:
Stack(int size) {
this -> size = size;
arr = new int[size];
top = -1;
}
void push(int element) {
if(size - top > 1)
arr[++top] = element;
else
cout << "<< Stack Overflow!! \nBecause you're trying to push <" << element << "> into the stack >>" << endl;
}
void pop() {
if(isEmpty())
cout << "Stack Underflow !" << endl;
else
top--;
}
void peak () {
if(isEmpty())
cout << "Stack is Empty !" << endl;
else
cout << arr[top] << endl;
}
bool isEmpty() {
if(top == -1)
return true;
else
return false;
}
};
int main() {
int size = 5;
Stack s(size);
s.push(100);
// inserting/pushing elements
for (int i = 0; i < size; i++)
s.push(i+1);
// 100,1,2,3,4,5 -> beacuse of 5 else statment will be printed
// printng & popping
cout << endl << "printing & popping elements! " << endl;
while(!s.isEmpty()) {
s.peak(); //
s.pop();
}
s.peak();
s.pop();
}
Last updated
Was this helpful?