1 #ifndef __QUEUE_H_
2 #define __QUEUE_H_
3
4 template<typename T>
5 class IQueue
6 {
7 public:
8 virtual ~IQueue(){}
9 virtual int push(const T &t) = 0;
10 virtual int front(const T **pt) = 0;
11 virtual int pop(T *t) = 0;
12 virtual bool empty() = 0;
13 };
14
15 class SimpleQueue : public IQueue<int>
16 {
17 public:
18 SimpleQueue(const int maxSize = 1024*1024)
19 : _queue(NULL), _size(maxSize), _head(0), _tail(0), _full(false), _valid(false)
20 {
21 if (0 >= _size) return ;
22 _queue = new (std::nothrow) int[_size];
23 if (NULL == _queue) return ;
24 _valid = true;
25 }
26
27 ~SimpleQueue()
28 {
29 if (NULL != _queue) {
30 delete [] _queue;
31 _queue = NULL;
32 }
33 }
34
35 int push(const int &a)
36 {
37 if (!_valid || _full) return -1;
38 _queue[_tail] = a;
39 ++_tail;
40 if (_tail >= _size) _tail = 0;
41 if (_head == _tail) _full = true;
42 return 0;
43 }
44
45 int front(const int ** ppa)
46 {
47 if (!_valid || NULL == ppa || _head == _tail) return -1;
48 *ppa = &_queue[_head];
49 return 0;
50 }
51
52 int pop(int * pa)
53 {
54 if (!_valid || NULL == pa || (_head == _tail && !_full) ) return -1;
55 *pa = _queue[_head++];
56 if (_head >= _size) _head = 0;
57 return 0;
58 }
59
60 bool empty()
61 {
62 return (!_valid || _head == _tail);
63 }
64
65 private:
66 int * _queue;
67 int _size;
68 int _head;
69 int _tail;
70 bool _full;
71 bool _valid;
72 };