Stack
Sat Aug 13 2022 11:32:29 GMT+0000 (Coordinated Universal Time)
Saved by
@sahmal
#cpp
#include<iostream>
using namespace std;
#define n 100
//stack class
class stack{
public:
int *arr;
int top;
//constructor for allocating memory
stack()
{
arr = new int[n];
top = -1;
}
//push function to insert an element at the top of stack
void push(int data)
{
if(this->top==n-1)
{
cout << "no space for the new element " << endl;
return;
}
++top;
arr[top] = data;
return;
}
//Function for removing the element from the top of the stack
void pop()
{
if(top==-1)
{
cout << "Empty Stack " << endl;
return;
}
top--;
}
//Function to get the top element value
int Top()
{
if(top==-1)
{
cout << "Empty Stack " << endl;
return -1;
}
if(top>n-1)
{
cout << "stack overflow " << endl;
return -1;
}
return arr[top];
}
//Function to check is stack is empty or not
bool empty()
{
return top == -1;
}
//Function for printing the stack
void print()
{
if(top==-1)
{
cout << "Empty Stack " << endl;
return;
}
for (int i = 0; i <= top;i++)
{
cout << arr[i] << " ";
}
return;
}
~stack()
{
delete arr;
}
};
//main function
int main()
{
//making object of stack class
stack object;
object.push(1);
object.push(2);
object.push(3);
object.push(4);
cout << "1st print " << endl;
object.print();
object.pop();
cout << endl;
cout << "2nd print" << endl;
object.print();
cout << endl;
cout<< object.Top();
cout << endl;
//checking if the stack is Empty
cout<<object.empty();
cout << endl;
return 0;
}
content_copyCOPY
Stack simple operations push,pop,top,empty
Comments