sidrs

FDS (LV) Ass 4 - Stack Ops

Aug 26th, 2024
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Stack {
  5.     int stackSize;
  6.     int stack[stackSize];
  7.     int tos;
  8. public:
  9.     Stack(int sz) {
  10.         tos = 0;
  11.         stackSize = sz;
  12.         stack[sz] = {0};
  13.     }
  14.  
  15.     void push(int n){
  16.         if (tos < stackSize){
  17.             if (tos == stackSize - 1) {
  18.                 stack[tos] = n;
  19.             } else {
  20.                 stack[tos] = n;
  21.                 tos++;
  22.             }
  23.         } else if (tos > stackSize - 1) {
  24.             cout << "STACK OVERFLOW! CANNOT PUSH\n";
  25.             tos = stackSize - 1;
  26.         }
  27.     }
  28.  
  29.     void pop(){
  30.         int data = 0;
  31.         if (tos == -1){
  32.             cout << "STACK UNDERFLOW! CANNOT POP\n";
  33.             tos = 0;
  34.         } else if (tos == 0) {
  35.             data = stack[0];
  36.             cout << "Data: " << data << " has been popped\n";
  37.         } else {
  38.             data = stack[tos];
  39.             cout << "Data: " << data << "has been popped\n";
  40.             tos--;
  41.         }
  42.     }
  43.  
  44.     void display(){
  45.         for (int i = tos - 1; i >= 0; i--){
  46.             cout << stack[tos] << endl;
  47.         }
  48.     }
  49. };
  50.  
  51.  
  52. int main(){
  53.     Stack ds(5);
  54.     ds.push(1); //tos = 0
  55.     ds.push(2); // 1
  56.     ds.push(3);
  57.     ds.push(4);
  58.     ds.push(5);
  59.     ds.display();
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment