stcktp1.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // stcktp1.h -- modified Stack template
  2. #ifndef STCKTP1_H_
  3. #define STCKTP1_H_
  4. template <class Type>
  5. class Stack
  6. {
  7. private:
  8. enum {SIZE = 10}; // default size
  9. int stacksize;
  10. Type * items; // holds stack items
  11. int top; // index for top stack item
  12. public:
  13. explicit Stack(int ss = SIZE);
  14. Stack(const Stack & st);
  15. ~Stack() { delete [] items; }
  16. bool isempty() { return top == 0; }
  17. bool isfull() { return top == stacksize; }
  18. bool push(const Type & item); // add item to stack
  19. bool pop(Type & item); // pop top into item
  20. Stack & operator=(const Stack & st);
  21. };
  22. template <class Type>
  23. Stack<Type>::Stack(int ss) : stacksize(ss), top(0)
  24. {
  25. items = new Type [stacksize];
  26. }
  27. template <class Type>
  28. Stack<Type>::Stack(const Stack & st)
  29. {
  30. stacksize = st.stacksize;
  31. top = st.top;
  32. items = new Type [stacksize];
  33. for (int i = 0; i < top; i++)
  34. items[i] = st.items[i];
  35. }
  36. template <class Type>
  37. bool Stack<Type>::push(const Type & item)
  38. {
  39. if (top < stacksize)
  40. {
  41. items[top++] = item;
  42. return true;
  43. }
  44. else
  45. return false;
  46. }
  47. template <class Type>
  48. bool Stack<Type>::pop(Type & item)
  49. {
  50. if (top > 0)
  51. {
  52. item = items[--top];
  53. return true;
  54. }
  55. else
  56. return false;
  57. }
  58. template <class Type>
  59. Stack<Type> & Stack<Type>::operator=(const Stack<Type> & st)
  60. {
  61. if (this == &st)
  62. return *this;
  63. delete [] items;
  64. stacksize = st.stacksize;
  65. top = st.top;
  66. items = new Type [stacksize];
  67. for (int i = 0; i < top; i++)
  68. items[i] = st.items[i];
  69. return *this;
  70. }
  71. #endif