Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- template<typename T> class CStack {
- public:
- static enum {CStack_StackEmpty, CStack_BadMemory};
- unsigned int size()
- {
- return StackSize;
- }
- bool empty()
- {
- return StackSize == 0;
- }
- T pop()
- {
- T top = 0;
- if(StackSize != 0)
- {
- top = _Stack[StackSize-1];
- T* _newstack = (T*)malloc(--StackSize * sizeof(T));
- if(_newstack == NULL)
- {
- throw (int)CStack_BadMemory;
- }
- for(int i=0;i<StackSize;i++)
- {
- _newstack[i] = _Stack[i];
- }
- free(_Stack);
- _Stack = _newstack;
- return top;
- } else
- {
- throw (int)CStack_StackEmpty;
- }
- }
- void push(T j)
- {
- T* _newstack = (T*)malloc(++StackSize * sizeof(T));
- if(_newstack == NULL)
- {
- throw (int)CStack_BadMemory;
- }
- if(_Stack != NULL)
- {
- for(int i=0;i<StackSize-1;i++)
- {
- _newstack[i] = _Stack[i];
- }
- free(_Stack);
- }
- _Stack = _newstack;
- _Stack[StackSize-1] = j;
- }
- void clear()
- {
- free(_Stack);
- _Stack = NULL;
- StackSize = 0;
- }
- CStack()
- {
- StackSize = 0;
- _Stack = NULL;
- }
- ~CStack()
- {
- free(_Stack);
- StackSize = 0;
- }
- private:
- unsigned int StackSize;
- T* _Stack;
- };
- int main(void)
- {
- CStack<int> s;
- for(int i=0;i<=10;i++)
- {
- s.push(i*i);
- }
- try
- {
- for(int i=0;i<=100;i++)
- {
- printf("%d\n",s.pop());
- }
- }
- catch(int ex)
- {
- printf(ex == static_cast<int>(CStack<int>::CStack_StackEmpty) ? "Stack is empty" : "Can not alloc memory");
- }
- getchar();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment