-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.h
116 lines (98 loc) · 2.1 KB
/
queue.h
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
template <typename T>
class Queue
{
public:
Queue();
~Queue();
Queue(const Queue<T>& other);
void Push(T data);
void Pop();
T Front();
private:
struct Node
{
Node* prev;
T data;
};
Node* m_Front;
Node* m_Tail;
};
/************************************************************************************/
template <typename T>
Queue<T>::Queue() : m_Front(nullptr), m_Tail(nullptr) {}
template <typename T>
Queue<T>::~Queue()
{
while(m_Front)
{
Node* temp = m_Front;
m_Front = m_Front->prev;
delete temp;
}
}
template <typename T>
Queue<T>::Queue(const Queue<T>& other)
: m_Front(nullptr), m_Tail(nullptr)
{
if(other.m_Tail && other.m_Front)
{
Node* otherCurrentNode = other.m_Front;
Node* thisCurrentNode = m_Front;
while(otherCurrentNode)
{
// create new node
Node* newNode = new Node;
newNode->data = otherCurrentNode->data;
newNode->prev = nullptr;
// if this front is not set yet
if(!m_Front)
{
m_Front = newNode;
thisCurrentNode = m_Front;
}
else
{
thisCurrentNode->prev = newNode;
thisCurrentNode = newNode;
}
// if we are at the tail of the other queue
if(!otherCurrentNode->prev)
{
m_Tail = newNode;
}
otherCurrentNode = otherCurrentNode->prev;
}
}
}
template <typename T>
void Queue<T>::Push(T data)
{
Node* node = new Node;
node->data = data;
node->prev = nullptr;
if(m_Tail)
{
m_Tail->prev = node;
}
m_Tail = node;
if(!m_Front)
{
m_Front = node;
}
}
template <typename T>
void Queue<T>::Pop()
{
Node* temp = m_Front->prev;
delete m_Front;
m_Front = temp;
}
template <typename T>
T Queue<T>::Front()
{
if(m_Front)
{
return m_Front->data;
}
throw std::exception();
}