Stack Implementation in C++
As we know that the stack is very popular data structure. There are main two operations push and pop in stack. A stack is an ordered collection of items into which insertion and deletion operations occurs at only one end, called top of the stack (TOS). Learn more about stack here.
Here in C++ code we are going to implement the abstract concept of stack. We define four functions such that:
1. isFull()
Check whether the stack is full or not.
- if TOS == max-1, return true
- else return false
2. isEmpty()
Check whether the stack is empty or not.
- if TOS == -1, return true
- else return false
3. push()
Insert new element at new position of TOS.
- if isFull(), then display "stack is full" and stop
- read data
- TOS = TOS + 1
- stack [TOS] = data
- stop
4. pop()
Delete element from TOS.
- if isEmpty(), then display "stack is empty" and stop
- item = stack [TOS]
- TOS = TOS - 1
- return item
# include <iostream>
# include <stdlib.h>
using std::cin;
using std::cout;
using std::endl;
# define max 5
bool isFull(int * tos, int *stack){
if(*tos >= max-1)
return true;
else
return false;
}
bool isEmpty(int *tos, int *stack){
if(*tos <= -1)
return true;
else
return false;
}
void push(int * tos, int* stack){
if(isFull(tos, stack)){
cout<<"Stack is full"<<endl;
}
else{
int el;
cout<<"Enter element for push: ";
cin>>el;
stack[++(*tos)] = el;
cout<<"Push completed !!"<<endl;
}
}
void pop(int* tos, int* stack){
if(isEmpty(tos, stack)){
cout<<"Stack is empty"<<endl;
}
else{
int el;
el = (stack[*tos]);
--(*tos);
cout<<"Poped element: "<<el<<endl;
}
}
void display(int* tos, int* stack){
if(isEmpty(tos, stack))
cout<<"Sorry, Stack is empty."<<endl;
else{
cout<<"Elements in stack:"<<endl;
if((*tos)>=0){
for(int i=0; i<=(*tos); i++){
cout<<stack[i]<<" ";
}
cout<<endl;
}
}
}
int main(){
int tos = -1;
int stack[max];
while(1){
int choice;
cout<<"\n1. Push\n2. Pop\n3. Display\n4. Exit\n"<<endl;
cin>>choice;
switch(choice){
case 1: push(&tos, &stack[0]);
break;
case 2: pop(&tos, &stack[0]);
break;
case 3:
display(&tos, &stack[0]);
break;
case 4:
cout<<"Exiting...";
exit(0);
default:
cout<<"Enter valid input !!"<<endl;
}
}
return 0;
}
Comments
Post a Comment