spider68

find the middle element of a stack

Jul 16th, 2021
1,406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.03 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class stack{
  6.     int size,last;
  7.     int*arr;
  8.     public:
  9.         stack(int n){
  10.             size=n;
  11.             last=-1;
  12.             arr=new int[n];
  13.         }
  14.         void push(int x){
  15.             if(last==size-1)cout<<"FULL\n";
  16.             else{
  17.                 last++;
  18.                 arr[last]=x;
  19.                 cout<<"Push: "<<x<<endl;
  20.             }
  21.         }
  22.         void pop(){
  23.             if(last==-1)cout<<"Empty\n";
  24.             else{
  25.                 int x=arr[last];
  26.                 last--;
  27.                 cout<<"Pop: "<<x<<endl;
  28.             }
  29.         }
  30.         void middle(){
  31.             if(last==-1)cout<<"empty\n";
  32.             else{
  33.                 cout<<"Middle: "<<arr[last/2]<<endl;
  34.             }
  35.         }
  36. };
  37. int main()
  38. {
  39.    stack st(3);
  40.    st.push(1);
  41.    st.middle();
  42.    st.push(2);
  43.    st.push(3);
  44.    st.middle();
  45.    st.push(4);
  46.    st.middle();
  47.    st.push(5);
  48.    st.pop();
  49.    st.pop();
  50.    
  51.    st.push(6);
  52.    st.middle();
  53.    return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment