Stack.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Project: Stack.cbp
  2. // File : Stack.h
  3. #ifndef STACK_H
  4. #define STACK_H
  5. #include "Node.h"
  6. template <typename T>
  7. class Stack
  8. {
  9. private:
  10. int m_count;
  11. Node<T> * m_top;
  12. public:
  13. Stack();
  14. bool IsEmpty();
  15. T Top();
  16. void Push(T val);
  17. void Pop();
  18. };
  19. template <typename T>
  20. Stack<T>::Stack() : m_count(0), m_top(NULL) {}
  21. template <typename T>
  22. bool Stack<T>::IsEmpty()
  23. {
  24. // return TRUE if there are no items
  25. // otherwise, return FALSE
  26. return m_count <= 0;
  27. }
  28. template <typename T>
  29. T Stack<T>::Top()
  30. {
  31. // Just return the value
  32. // of m_top node
  33. return m_top->Value;
  34. }
  35. template <typename T>
  36. void Stack<T>::Push(T val)
  37. {
  38. // Create a new Node
  39. Node<T> * node = new Node<T>(val);
  40. // The Next pointer of this new node
  41. // will point to current m_top node
  42. node->Next = m_top;
  43. // The new Node now becomes the m_top node
  44. m_top = node;
  45. // One item is added
  46. m_count++;
  47. }
  48. template <typename T>
  49. void Stack<T>::Pop()
  50. {
  51. // Do nothing if Stack is empty
  52. if(IsEmpty())
  53. return;
  54. // Prepare the current m_top
  55. // to remove
  56. Node<T> * node = m_top;
  57. // The new m_top node will be
  58. // the Next pointer of the current m_top node
  59. m_top = m_top->Next;
  60. // Now it's safe to remove
  61. // the first element
  62. delete node;
  63. // One item is removed
  64. m_count--;
  65. }
  66. #endif // STACK_H