Advertisement
Masfiq_ds_algo

DS: 2 stacks using 1 array

Feb 25th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. /*
  2. *   masfiq
  3. *   17 march, 2017
  4. *
  5. */
  6. #include<iostream>
  7. #include<cstdlib>
  8. using namespace std;
  9.  
  10. class twoStacks
  11. {
  12. private:
  13.     int *arr;
  14.     int size;
  15.     int top1;
  16.     int top2;
  17. public:
  18.     twoStacks(int size)  //Constructor
  19.     {
  20.         this->size = size;
  21.         this->arr = new int[size];
  22.         top1 = -1;
  23.         top2 = size;
  24.     }
  25.     void push1(int x)
  26.     {
  27.         if(top2 == top1+1)
  28.         {
  29.             cout<<"stack overflowed."<<endl;
  30.             exit(1);
  31.         }
  32.         else
  33.         {
  34.             top1++;
  35.             arr[top1] = x;
  36.         }
  37.     }
  38.     void push2(int x)
  39.     {
  40.         if(top2 == top1+1)
  41.         {
  42.             cout<<"stack overflowed."<<endl;
  43.             exit(1);
  44.         }
  45.         else
  46.         {
  47.             top2--;
  48.             arr[top2] = x;
  49.         }
  50.     }
  51.     int pop1()
  52.     {
  53.         if(top1 == -1)
  54.         {
  55.             cout<<"stack underflowed."<<endl;
  56.             exit(1);
  57.         }
  58.         else
  59.         {
  60.             int x = arr[top1];
  61.             top1--;
  62.             return x;
  63.         }
  64.     }
  65.     int pop2()
  66.     {
  67.         if(top2 == size)
  68.         {
  69.             cout<<"stack underflowed"<<endl;
  70.             exit(1);
  71.         }
  72.         else
  73.         {
  74.             int x = arr[top2];
  75.             top2++;
  76.             return x;
  77.         }
  78.     }
  79. void print_stack1(){
  80.     for(int i=0; i<= top1; i++){
  81.         cout<<arr[i]<<"->";
  82.     }
  83.     cout<<endl;
  84. }
  85. void print_stack2(){
  86.     for(int i=size-1; i >= top2; i--){
  87.         cout<<arr[i]<<"->";
  88.     }
  89.     cout<<endl;
  90. }
  91. };
  92.  
  93. int main()
  94. {
  95.     twoStacks ts(5);
  96.     ts.push1(5);
  97.     ts.push2(10);
  98.     ts.push2(15);
  99.     ts.push1(11);
  100.     ts.push2(7);
  101.     ts.print_stack1();
  102.     ts.print_stack2();
  103. //    cout << "Popped element from stack1 is " << ts.pop1();
  104. //    ts.push2(40);
  105. //    cout << "\nPopped element from stack2 is " << ts.pop2();
  106.  
  107.     return 0;
  108. }
  109. /*
  110.     Output:
  111.     5->11->
  112.     10->15->7->
  113. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement