forked from Silver-Taurus/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.h
113 lines (96 loc) · 3.56 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
/***
* _ __ ___ _
* | |/ /___ ___ _ __ / __|__ _| |_ __
* | ' </ -_) -_) '_ \ | (__/ _` | | ' \
* |_|\_\___\___| .__/ \___\__,_|_|_|_|_|
* |_|
* _
* __ _ _ _ __| |
* / _` | ' \/ _` |
* \__,_|_||_\__,_|
*
* _ _ _ _ _ _
* | | ___ __ _ _ _ _ _ /_\ | |__ _ ___ _ _(_) |_| |_ _ __ ___
* | |__/ -_) _` | '_| ' \ / _ \| / _` / _ \ '_| | _| ' \| ' \(_-<
* |____\___\__,_|_| |_||_| /_/ \_\_\__, \___/_| |_|\__|_||_|_|_|_/__/
* |___/
* Yeah! Ravi let's do it!
*/
#ifndef QUEUE_H
#define QUEUE_H
#include <exception>
namespace algo {
const int defaultQueueCapacity = 500;
template <typename T>
class Queue {
public:
Queue( int capacity = defaultQueueCapacity )
: _capacity { capacity }, _count { 0 },
_head { 0 }, _tail { -1 }, _elements { new T[_capacity] }
{
}
bool empty() const
{
return ( _count == 0 );
}
int count() const
{
return _count;
}
int capacity() const
{
return _capacity;
}
void pop()
{
if (empty())
{
return;
}
else {
--_count;
++_head;
if ( _head == _capacity ) {
_head = 0;
}
}
}
bool push( const T & obj )
{
if ( _count == _capacity )
{
return false;
}
else {
++_count;
++_tail;
if ( _tail == _capacity )
{
_tail = 0;
}
_elements[_tail] = obj;
return true;
}
}
const T & front() const
{
if ( empty() ) throw empty_queue_exception;
return _elements[_head];
}
private:
class EmptyQueueException : public std::exception {
virtual const char * what() const throw()
{
return "Queue is empty";
}
} empty_queue_exception;
int _capacity;
int _count;
int _head;
int _tail;
T * _elements;
Queue( const Queue & );
Queue & operator= ( const Queue & );
}; //end of class queue
} //end of namespace algo
#endif //end of QUEUE_H