-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueue.h
95 lines (76 loc) · 1.97 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
#pragma once
#include <iostream>
#include <stdexcept>
using namespace std;
template<class T>
class Queue
{
// FIFO objects
public:
Queue(int MaxQueueSize = 10);
Queue(Queue<T> &Q);
~Queue() { delete[] queue; }
bool IsEmpty() const { return front == rear; }
bool IsFull() const
{
if ((rear + 1) % MaxSize == front) return 1;
else return 0;
}
T Front() const; // return front element
void enqueue(const T& x);
void dequeue();
int getMaxSize() const { return MaxSize; }
private:
int front; // one counterclockwise from first
int rear; // last element
int MaxSize; // size of array queue
T *queue; // element array
};
template<class T>
Queue<T>::Queue(int MaxQueueSize)
{// Create an empty queue whose capacity
// is MaxQueueSize.
MaxSize = MaxQueueSize + 1;
queue = new T[MaxSize];
front = rear = 0;
}
template<class T>
Queue<T>::Queue(Queue<T> &Q)
{
int i;
front = 0; rear = 0;
MaxSize = Q.getMaxSize();
queue = new T[MaxSize];
while (!Q.IsEmpty())
{
queue[rear] = Q.Front();
Q.dequeue();
rear = (rear + 1) % MaxSize;
}
for (i = front; i != rear; i = (i + 1) % MaxSize)
Q.enqueue(queue[i]);
}
template<class T>
T Queue<T>::Front() const
{// Return first element of queue. Throw
// OutOfBounds exception if the queue is empty.
if (IsEmpty())
throw logic_error("Queue exception: cannot retrieve from empty queue ");
return queue[front];
}
template<class T>
void Queue<T>::enqueue(const T& x)
{// Add x to the rear of the queue. Throw
// NoMem exception if the queue is full.
if (IsFull()) throw logic_error("Queue exception: Queue is full ");
queue[rear] = x;
rear = (rear + 1) % MaxSize;
}
template<class T>
void Queue<T>::dequeue()
{// Delete first element and put in x. Throw
// OutOfBounds exception if the queue is empty.
if (IsEmpty())
throw logic_error("Queue exception: cannot delete from empty queue ");
front = (front + 1) % MaxSize;
}