Stack.h 1.3 KB

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