thespeedracer38

Stack Improved

Jan 14th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. using namespace std;
  5.  
  6. class Stack{
  7.     private:
  8.         int *arr;
  9.         int top;
  10.         int size;
  11.     public:
  12.         Stack();
  13.         Stack(int);
  14.         ~Stack();
  15.         void push(int);
  16.         int pop();
  17. };
  18.  
  19. Stack::Stack(){
  20.     top = -1;
  21.     size = 100;
  22.     arr = new int[size];
  23. }
  24.  
  25. Stack::Stack(int size){
  26.     top = -1;
  27.     this->size = size;
  28.     arr = new int[this->size];
  29. }
  30.  
  31. Stack::~Stack(){
  32.     delete[] arr;
  33. }
  34.  
  35. void Stack::push(int item){
  36.     if(top == (size - 1)){
  37.         cout << "STACK OVERFLOW" << endl;
  38.     }
  39.     else{
  40.         top = top + 1;
  41.         arr[top] = item;
  42.         cout << item << " pushed" << endl;
  43.     }
  44. }
  45.  
  46. int Stack::pop(){
  47.     int ret  = -1;
  48.     if(top == -1){
  49.         cout << "STACK UNDERFLOW" << endl;
  50.     }
  51.     else{
  52.         ret = arr[top];
  53.         top = top - 1;
  54.     }
  55.     return ret;
  56. }
  57.  
  58. int main() {
  59.     system("cls");
  60.     int size;
  61.     cout << "Enter the size of the stack: ";
  62.     cin >> size;
  63.     Stack obj(size);
  64.     int choice;
  65.     do {
  66.         cout << "Press 1 to push an element\n";
  67.         cout << "Press 2 to pop an element\n";
  68.         cout << "Press 3 to quit\n";
  69.         cout << "Enter your choice: ";
  70.         cin >> choice;
  71.         int temp;
  72.         switch(choice){
  73.             case 1:
  74.                 cout << "Enter item: ";
  75.                 cin >> temp;
  76.                 obj.push(temp);
  77.                 break;
  78.             case 2:
  79.                 temp = obj.pop();
  80.                 if(temp != -1)
  81.                     cout << temp << " popped" << endl;
  82.                 break;
  83.             case 3:
  84.                 break;
  85.             default:
  86.                 cout << "Invalid choice" << endl;
  87.         }  
  88.     }while(choice != 3);
  89.     return 0;
  90. }
Add Comment
Please, Sign In to add comment