-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.hpp
96 lines (83 loc) · 1.74 KB
/
Queue.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
A queue implemented with dynamic memory
Gilberto Echeverria
*/
#ifndef QUEUE_HPP
#define QUEUE_HPP
#include <iostream>
#include "Node.hpp"
template <class T>
class Queue {
private:
Node<T> * head = nullptr;
Node<T> * tail = nullptr;
public:
Queue () {}
Queue (Node<T> * new_node)
{ head = new_node; tail = new_node; }
~Queue() { clear(); }
bool isEmpty() { return head == nullptr; }
Node<T> * top();
Node<T> * pop();
void push(Node<T> * new_node);
void push(T data);
void clear();
};
template <class T>
Node<T> * Queue<T>::top()
{
return head;
}
template <class T>
Node<T> * Queue<T>::pop()
{
// If the list was empty
if(head == nullptr)
return nullptr;
Node<T> * item = head;
// Update the head in the list
head = head->getNext();
// If there was only one element in the list
if (head == nullptr)
tail = nullptr;
// Break the connection to the list
item->setNext(nullptr);
return item;
}
template <class T>
void Queue<T>::push(Node<T> * new_node)
{
// If the queue is empty
if (tail == nullptr)
{
tail = new_node;
head = new_node;
}
else
{
// Add the new node at the tail
tail->setNext(new_node);
// Update the pointer
tail = new_node;
}
}
template <class T>
void Queue<T>::push(T data)
{
Node<T> * new_item = new Node<T>(data);
push(new_item);
}
template <class T>
void Queue<T>::clear()
{
Node<T> * item = head;
while (item != nullptr)
{
head = item->getNext();
delete item;
item = head;
}
tail = nullptr;
}
#endif