Aim:
write a C++ program to Implementation of Multistack in a Single Array.
Program:
#include <iostream.h> #define max 10 class multistack { int top1, top2, stk_arr[max]; public: multistack() { top1=-1; top2=max; } void push() { int x,ch; if(top1==top2-1) { cout<<"stack overflow "<<endl; return; } cout<<"enter a no \n"; cin>>x; cout<<"\n press 1 to push in stack1 or press 2 for stack2:"; cin>>ch; if(ch==1) stk_arr[++top1]=x; else stk_arr[--top2]=x; cout<< x <<" element is successfully pushed \n"; return; } void pop() { int y,ch; cout<<"\n press 1 to pop from stack1 or press 2 for stack2"; cin>>ch; if(ch==1) { if(top1==-1) { cout<<"stack underflow\n"; return; } y=stk_arr[top1]; stk_arr[top1--]=0; } else { if(top2==max) { cout<<"stack underflow\n"; return; } y=stk_arr[top2]; stk_arr[top2++]=0; } cout<<y<< "\n element is successfully poped from stack \n"; return; } void display() { int i; if (top1 == -1) { cout<<"stack 1 is empty \n"; } else { cout<<"elements of Stack 1 are : \n"; for (i = 0; i <= top1; i++) { cout<<stk_arr[i]<<endl; } } if (top2 == max) { cout<<"stack 2 is empty \n"; } else { cout<<"elements of Stack 2 are : \n"; for (i = max-1; i >= top2; i--) { cout<<stk_arr[i]<<endl; } } return ; } }; main() { multistack s; int ch; do { cout<<"\n 1:push\n 2:pop\n 3:display\n 4:exit\n choice:"; cin>>ch; switch (ch) { case 1:s.push(); break; case 2:s.pop(); break; case 3:s.display(); break; case 4:cout<<"exiting from program\n"; break; default:cout<<"wrong choice\n"; break; } }while(ch!=4); }
Output:
1:Push 2:Pop 3:Display 4:Exit Choice: 1 Enter a no 10 Press 1 to push in stack 1 or press 2 for stack 2 : 1 10 element is successfully pushed 1:Push 2:Pop 3:Display 4:Exit Choice: 1 Enter a no 20 Press 1 to push in stack 1 or press 2 for stack 2 : 1 20 element is successfully pushed 1:Push 2:Pop 3:Display 4:Exit Choice: 1 Enter a no 100 Press 1 to push in stack 1 or press 2 for stack 2 : 2 100 element is successfully pushed 1:Push 2:Pop 3:Display 4:Exit Choice: 3 Elements of stack 1 are: 20 10 Elements of stack 2 are: 200 100 1:Push 2:Pop 3:Display 4:Exit Choice: 2 Press 1 to pop from stack 1 or press 2 for stack 2: 1 20 Element is successfully poped from stack 1:Push 2:Pop 3:Display 4:Exit Choice: 2 Press 1 to pop from stack 1 or press 2 for stack 2: 2 200 Element is successfully poped from stack 1:Push 2:Pop 3:Display 4:Exit Choice: 3 Elements of stack 1 are: 10 Elements of stack 2 are: 100
Result:
Thus, the Implementation of Multistack in a Single Array was successfully executed.