-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcircular_queue.h
117 lines (97 loc) · 2.33 KB
/
circular_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
117
/*
* circular_queue.h
*
* Created on: 2011-10-22
* Author: gxl2007@hotmail.com
*/
#ifndef CIRCULAR_QUEUE_H_
#define CIRCULAR_QUEUE_H_
#include <new>
namespace xlnet
{
/*
* @brief circular queue , push elements at the head and pop elements at the tail
*/
template<typename T>
class circular_queue
{
public:
/*
* @brief initialize the queue , allocate space
*/
int init(int maxsize)
{
if ( m_itemlist != NULL || maxsize < 4 ) return -1 ;
m_itemlist = new T[maxsize] ;
if ( m_itemlist == NULL ) return -1 ;
m_maxsize = maxsize ;
return 0 ;
} ;
/*
* @brief clean up
*/
void fini()
{
if ( m_itemlist != NULL )
{
delete[] m_itemlist ;
m_itemlist = NULL ;
m_front = m_back = 0 ;
}
} ;
/*
* @brief get the queue capacity size
*/
int capacity() const { return m_maxsize ;} ;
/*
* @brief check the queue is empty
* @return true if empty
*/
bool empty() const { return m_front == m_back ;} ;
/*
* @brief check the queue is full
* @return true if full
*/
bool full() const {return (m_front +1) % m_maxsize == m_back ; } ;
/*
* @brief push element at the head
*/
int push(const T& element)
{
if ( full() ) return -1 ;
m_itemlist[m_front] = element ;
m_front = (m_front +1) % m_maxsize ;
return 0 ;
}
/*
* @brief pop element at the tail
*/
int pop(T& element)
{
if ( empty() ) return -1 ;
element = m_itemlist[m_back] ;
m_back = (m_back +1) % m_maxsize ;
return 0 ;
}
/*
* @brief get the tail element pointer
*/
T* back()
{
if (m_itemlist == NULL || empty() ) return NULL ;
return m_itemlist + m_back ;
} ;
public:
circular_queue():m_maxsize(1),m_itemlist(NULL),m_front(0),m_back(0){};
~circular_queue() { fini(); } ;
private:
circular_queue(const circular_queue&) ;
circular_queue& operator=(const circular_queue&) ;
private:
int m_maxsize ;
T* m_itemlist ;
volatile int m_front ;
volatile int m_back ;
};
}
#endif /* CIRCULAR_QUEUE_H_ */