Implementation of Stack in C++
#include<iostream>
#include<cstdlib>
#define MAX_SIZE 20
using namespace std;
class Stack{
private:
int item[MAX_SIZE];
int top;
public:
Stack(){
top = -1;
}
void push(int data){
item[++top] = data;
}
int pop(){
return item[top--];
}
int size(){
return top+1;
}
bool is_empty(){
if(top==-1)
return true;
else
return false;
}
bool is_full(){
if(top==MAX_SIZE-1)
return true;
else
return false;
}
void display(){
for(int i=0; i<this->size(); i++){
cout<<item[i]<<" ";
}
cout<<endl;
}
};
int main(){
int input;
int temp;
Stack stack;
while(true){
cout<<"Choose any one of the following"<<endl;
cout<<"1. Push Item. "<<endl;
cout<<"2. Pop Item."<<endl;
cout<<"3. Display all elements of stack."<<endl;
cout<<"4. Size of Stack."<<endl;
cout<<"5. Exit."<<endl;
cout<<"Your Choice: ";
cin>>input;
switch(input){
case 1:
if(!stack.is_full()){
cout<<"Enter number to push: ";
cin>>temp;
stack.push(temp);
}else{
cout<<"Can't push. Stack is Full!!"<<endl;
}
break;
case 2:
if(!stack.is_empty()){
cout<<"The number popped is: "<<stack.pop()<<endl;
}else{
cout<<"Cant't pop. Stack is Empty!!"<<endl;
}
break;
case 3:
if(!stack.is_empty()){
cout<<"The elements in stack are: ";
stack.display();
cout<<endl;
}else{
cout<<"Stack is Empty"<<endl;
}
break;
case 4:
cout<<"The size of the stack is: "<<stack.size()<<endl;
break;
case 5:
exit(0);
break;
}
}
return 0;
}
Implementation of Queue in C++
#include<iostream>
#define Maxsize 10
using namespace std;
class Queue
{
private:
int front;
int rear;
int queue[Maxsize];
public:
Queue()
{
front=0;
rear=-1;
}
void enqueue()
{
int data;
cout<<"Enter data to enqueue :";cin>>data;
if(rear==Maxsize-1)
cout<<"Queue is FULL .\n";
else
queue[++rear]=data;
}
int dequeue()
{
if(front>rear)
cout<<"Queue is EMPTY .\n";
else
{
int data=queue[front];
return data;
}
}
void display()
{
for(int i=0;i<=rear;i++)
cout<<queue[i]<<endl;
}
};
int main()
{
Queue q;
int res;
char choice;
cout<<"\n\tQueue Operation :\n\n";
cout<<"\n1.Enqueue \n";
cout<<"2.Dequeue \n";
cout<<"3.Display\n";
do{
cout<<"Enter your choice :1/2/3 :: ";
cin>>res;
switch(res)
{
case 1:q.enqueue();break;
case 2:q.dequeue();break;
case 3:q.display();
}
cout<<"Want to continue ? ";cin>>choice;
}while(choice=='y');
return 0;
}