Queue.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Project: Queue.cbp
  2. // File : Queue.h
  3. #ifndef QUEUE_H
  4. #define QUEUE_H
  5. #include "Node.h"
  6. template <typename T>
  7. class Queue
  8. {
  9. private:
  10. int m_count;
  11. Node<T> * m_front;
  12. Node<T> * m_back;
  13. public:
  14. Queue();
  15. bool IsEmpty();
  16. T Front();
  17. void Enqueue(T val);
  18. void Dequeue();
  19. };
  20. template <typename T>
  21. Queue<T>::Queue() : m_count(0), m_front(NULL), m_back(NULL) {}
  22. template <typename T>
  23. bool Queue<T>::IsEmpty()
  24. {
  25. // return TRUE if there's at least one item
  26. // otherwise, return FALSE
  27. return m_count <= 0;
  28. }
  29. template <typename T>
  30. T Queue<T>::Front()
  31. {
  32. // Just return the value
  33. // of m_front node
  34. return m_front->Value;
  35. }
  36. template <typename T>
  37. void Queue<T>::Enqueue(T val)
  38. {
  39. // Create a new Node
  40. Node<T> * node = new Node<T>(val);
  41. if(m_count == 0)
  42. {
  43. // If the queue is empty
  44. // the new node will be
  45. // m_front and m_back
  46. node->Next = NULL;
  47. m_front = node;
  48. m_back = m_front;
  49. }
  50. else
  51. {
  52. // If there's at least one element
  53. // in the queue, the current m_back element
  54. // won't be the Back element anymore
  55. // so the Next pointer of the current m_back
  56. // point to the new node
  57. m_back->Next = node;
  58. // The new Node now become the Back position
  59. m_back = node;
  60. }
  61. // One element is added
  62. m_count++;
  63. }
  64. template <typename T>
  65. void Queue<T>::Dequeue()
  66. {
  67. // Do nothing if list is empty
  68. if(m_count == 0)
  69. return;
  70. // Save the current Front
  71. // to a new node
  72. Node<T> * node = m_front;
  73. // Point the Front pointer
  74. // to the element next to the current Front
  75. m_front = m_front->Next;
  76. // Now it's safe to remove
  77. // the first element
  78. delete node;
  79. // One element is removed
  80. m_count--;
  81. }
  82. #endif // QUEUE_H