Stack In C++
Stack:
Stack is a type of a linear data structure which follows a particular order to store data for specific use. Stack follows LIFO(Last In First Out) or FILO(First In Last Out).
Real Life Examples of Stack:
1.Stack of plates:
In the above mention picture there is a stack of plates like the computer stack it follows LIFO or FILO like if I want to take a plate then I can take only upper plate this same concept follows in stack we can just access top element of a stack.
Operations on stack:
1.PUSH():
push operation used to enter the element at the top of stack.2.pop():
pop operation used to remove the top element form the stack and it return that element.
3.IsFull():
IsFull operation used to check the stack is full or not .If stack is full then this condition known as the overflow.
4.IsEmpty():
IsEmpty function used to check is stack is empty or not. If stack is empty then this condition known as the underflow.
5.peek():
Peek function is used for access element form stack.
6.change():
change function used for change the element at specific position in the stack.
Implementation of stack in c++ using array:
#include<iostream>
#include<string>
using namespace std;
class stack{
private:
int top;
int arr[5];
public:
stack(){
top=-1;
for(int i=0;i<5;i++){
arr[i]=0;
}
}
bool IsEmpty(){
if(top==-1)
return true;
else
return false;
}
bool IsFull(){
if(top==4)
return true;
else
return false;
}
void push(int val){
if(IsFull()){
cout<<"can't Push, stack overflow"<<endl;
}
else{
top++;
arr[top]=val;
}
}
int pop(){
if(IsEmpty()){
cout<<"stack underflow"<<endl;
return 0;
}
else{
int popval=arr[top];
arr[top]=0;
top--;
return popval;
}
}
int count(){
return top+1;
}
int peek(int pos){
if(IsEmpty()){
cout<<"stack underflow"<<endl;
return 0;
}
else{
return arr[pos];
}
}
void change(int pos, int val){
arr[pos]=val;
cout<<"value has been changed"<<endl;
}
void display(){
cout<<"stack is: "<<endl;
for(int i=4;i>-1;i--){
cout<<arr[i];
}
}
};
int main(){
stack s1;
int option, position , value;
do{
cout<<"0.exit"<<endl;
cout<<"1.push"<<endl;
cout<<"2.pop"<<endl;
cout<<"3.IsEmpty"<<endl;
cout<<"4.IsFull"<<endl;
cout<<"5.peek"<<endl;
cout<<"6.change"<<endl;
cout<<"7.display"<<endl;
cout<<"8.clear screen"<<endl;
cin>>option;
switch(option){
case 1:
cout<<"enter value for puch";
cin>>value;
s1.push(value);
break;
case 2:
cout<<"pop function is called"<<s1.pop();
break;
case 3:
if(s1.IsEmpty()){
cout<<"stack is Empty";
}
else{
cout<<"not Empty";
}
break;
case 4:
if(s1.IsFull()) {
cout<<"stack is full";
}
else{
cout<<"stack is not empty you can push values";
}
break;
case 5:
cout<<"Enter the position";
cin>>position;
cout<<"value at given position: "<<s1.peek(position);
break;
case 7:
s1.display();
break;
case 8:
system("cls");
break;
default:
cout<<" choose a correct option";
}
}
while (option!=0);
return 0;
}
0 Comments