/*
循环队列
enqueue: tail_loc = (tail_loc+1)%queue_size
dequeue: head = (head+1)%queue_size
empty:head=tail
full:(head+1)%queue_size = head
curr queue size: (tail - head))%queeu_size
*/
template<typename T>
class Queue{
private:
int queue_size;
T *data;
int head_loc;
int tail_loc;
public:
Queue(int queue_size=100);
~Queue();
void push(const T value);
void pop();
T front();
int get_size();
bool full();
bool empty();
};
template<typename T>
Queue<T>::Queue(int size){
head_loc = 0;
tail_loc = 0;
queue_size = size;
data = new T[size];
}
template<typename T>
Queue<T>::~Queue(){
delete []data;
data = nullptr;
head_loc = 0;
tail_loc = 0;
queue_size = 0;
}
template<typename T>
void Queue<T>::push(const T value){
if(full())
std::cerr<<"queue full"<<endl;
data[tail_loc] = value;
tail_loc = (tail_loc+1) % queue_size;
}
template<typename T>
T Queue<T>::front(){
if(empty())
std::cerr<<"queue empty"<<endl;
return data[head_loc];
}
template<typename T>
void Queue<T>::pop(){
if(empty())
std::cerr<<"queue empty"<<endl;
head_loc = (head_loc+1) % queue_size;
}
template<typename T>
bool Queue<T>::empty(){
return head_loc==tail_loc;
}
template<typename T>
bool Queue<T>::full(){
return (tail_loc+1)%queue_size==head_loc;
}
template<typename T>
int Queue<T>::get_size(){
return (tail_loc - head_loc + queue_size)%queue_size;
}
void print_queue(Queue<int> q){
while(!q.empty()){
cout<<q.front()<<endl;
q.pop();
}
}
int main(int argc, char const *argv[]){
Queue<int> q(100);
q.push(1);
q.push(2);
q.push(3);
q.push(4);
cout<<q.front()<<endl;
q.pop();
q.pop();
cout<<q.front()<<endl;
q.push(7);
print_queue(q);
return 0;
}