[cpp] Stack

Viewer

  1. #include <iostream>
  2.  
  3. const int MAX_SIZE = 10;
  4.  
  5. class Stack
  6. {
  7. public:
  8.     Stack()
  9.     {
  10.         size = MAX_SIZE;
  11.         items = new int[ size ];
  12.         top_index = -1;
  13.     }
  14.  
  15.     ~Stack()
  16.     {
  17.         delete[] items;
  18.     }
  19.  
  20.     void push( int value )
  21.     {
  22.         if( !full() )
  23.         {
  24.             ++top_index;
  25.             items[ top_index ] = value;
  26.         }
  27.         else
  28.         {
  29.             std::cerr << "Stos pełny!" << std::endl;
  30.         }
  31.     }
  32.  
  33.     int pop()
  34.     {
  35.         if( !empty() )
  36.         {
  37.             int popped = items[ top_index ];
  38.             --top_index;
  39.             return popped;
  40.         }
  41.         else
  42.         {
  43.             std::cerr << "Stos pusty!" << std::endl;
  44.             return -1;
  45.         }
  46.     }
  47.  
  48.     int top()
  49.     {
  50.         if( !empty() )
  51.         {
  52.             return items[ top_index ];
  53.         }
  54.         else
  55.         {
  56.             std::cerr << "Stos pusty!" << std::endl;
  57.             return -1;
  58.         }
  59.     }
  60.  
  61.     bool empty() const
  62.     {
  63.         return top_index == -1;
  64.     }
  65.  
  66.     bool full() const
  67.     {
  68.         return top_index == size - 1;
  69.     }
  70.  
  71.     void destroy()
  72.     {
  73.         top_index = -1;
  74.     }
  75.  
  76. private:
  77.     int* items;
  78.     int top_index;
  79.     int size;
  80. };
  81.  
  82. int main()
  83. {
  84.     Stack stack1;
  85.     Stack stack2;
  86.  
  87.     std::cout << "Wczytaj 10 liczb do stosu: " << std::endl;
  88.     for( int i = 0; i < 10; ++)
  89.     {
  90.         int num;
  91.         std::cin >> num;
  92.         stack1.push( num );
  93.     }
  94.  
  95.     std::cout << "Liczby ze stosu 1: " << std::endl;
  96.     while( !stack1.empty() )
  97.     {
  98.         int num = stack1.pop();
  99.         std::cout << num << std::endl;
  100.         stack2.push( num );
  101.     }
  102.  
  103.     std::cout << "Liczby ze stosu 1 po wypisaniu: " << std::endl;
  104.     while( !stack2.empty() )
  105.     {
  106.         int num = stack2.pop();
  107.         std::cout << num << std::endl;
  108.     }
  109.  
  110.     return 0;
  111. }
  112.  

Editor

You can edit this paste and save as new: