Pushok

Updated stack and exemple of using it

Apr 10th, 2011
500
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. template<typename T> class CStack {
  6. public:
  7.     static enum {CStack_StackEmpty, CStack_BadMemory};
  8.  
  9.     unsigned int size()
  10.     {
  11.         return StackSize;
  12.     }
  13.  
  14.     bool empty()
  15.     {
  16.         return StackSize == 0;
  17.     }
  18.  
  19.     T pop()
  20.     {
  21.         T top = 0;
  22.  
  23.         if(StackSize != 0)
  24.         {
  25.             top = _Stack[StackSize-1];
  26.  
  27.             T* _newstack = (T*)malloc(--StackSize * sizeof(T));
  28.  
  29.             if(_newstack == NULL)
  30.             {
  31.                 throw (int)CStack_BadMemory;
  32.             }
  33.  
  34.             for(int i=0;i<StackSize;i++)
  35.             {
  36.                 _newstack[i] = _Stack[i];
  37.             }
  38.  
  39.             free(_Stack);
  40.             _Stack = _newstack;
  41.  
  42.             return top;
  43.  
  44.         } else
  45.         {
  46.             throw (int)CStack_StackEmpty;
  47.         }
  48.     }
  49.  
  50.     void push(T j)
  51.     {
  52.         T* _newstack = (T*)malloc(++StackSize * sizeof(T));
  53.  
  54.         if(_newstack == NULL)
  55.         {
  56.             throw (int)CStack_BadMemory;
  57.         }
  58.  
  59.         if(_Stack != NULL)
  60.         {
  61.             for(int i=0;i<StackSize-1;i++)
  62.             {
  63.                 _newstack[i] = _Stack[i];
  64.             }
  65.  
  66.             free(_Stack);
  67.         }
  68.  
  69.         _Stack = _newstack;
  70.  
  71.         _Stack[StackSize-1] = j;
  72.     }
  73.  
  74.     void clear()
  75.     {
  76.         free(_Stack);
  77.         _Stack = NULL;
  78.         StackSize = 0;
  79.     }
  80.  
  81.     CStack()
  82.     {
  83.         StackSize = 0;
  84.         _Stack = NULL;
  85.     }
  86.  
  87.     ~CStack()
  88.     {
  89.         free(_Stack);
  90.         StackSize = 0;
  91.     }
  92.  
  93. private:
  94.     unsigned int StackSize;
  95.     T* _Stack;
  96. };
  97.  
  98. int main(void)
  99. {
  100.     CStack<int> s;
  101.  
  102.     for(int i=0;i<=10;i++)
  103.     {
  104.         s.push(i*i);
  105.     }
  106.  
  107.     try
  108.     {
  109.         for(int i=0;i<=100;i++)
  110.         {
  111.             printf("%d\n",s.pop());
  112.         }
  113.     }
  114.     catch(int ex)
  115.     {
  116.         printf(ex == static_cast<int>(CStack<int>::CStack_StackEmpty) ? "Stack is empty" : "Can not alloc memory");
  117.     }
  118.  
  119.     getchar();
  120.     return 0;
  121. }
Advertisement
Add Comment
Please, Sign In to add comment