C++动态数组实现队列

//Implementation of queue using dynamic array
#ifndef QUEUE_H
#define QUEUE_H

#include <iostream>
using namespace std;

template<typename T> class Queue
{
public:
int queueHead;
int queueTail;
int capacity;
T *arr;

bool isEmpty()
{
if(queueHead == queueTail)
return true;
else
return false;
}
bool isFull()
{
if(queueHead == (queueTail+1)%capacity)
return true;
else
return false;
}
int size()
{
return (capacity+queueTail-queueHead)%capacity;
}
void enQueue(T x)
{
if(isFull())
{
int index = 0;
capacity <<= 1;
T *temparr = new T[capacity];
for(int i=0;i<size();i++)
{
index = queueHead+i;
temparr[i] = arr[index];
}
delete[] arr;
arr = temparr;
queueTail = size();
queueHead = 0;
}
arr[queueTail] = x;
queueTail = (queueTail+1)%capacity;
}
T deQueue()
{
if(!isEmpty())
{
int preQueueHead = queueHead;
queueHead = (queueHead+1)%capacity;
return arr[preQueueHead];
}
else
{
cout<<"Queue underflow!"<<endl;
return NULL;
}
}
T getHead()
{
if(!isEmpty())
{
return arr[queueHead];
}
else
{
cout<<"Queue is empty!"<<endl;
return NULL;
}
}
T getTail()
{
if(!isEmpty())
{
return arr[(queueTail-1)%capacity];
}
else
{
cout<<"Queue is empty!"<<endl;
return NULL;
}
}
void show()
{
if(isEmpty())
cout<<"Queue is empty!"<<endl;
else
{
int index = 0;
for(int i=0;i<size();i++)
{
index = (queueHead+i)%capacity;
cout<<arr[index]<<" ";
}
cout<<endl;
}
}
Queue()
{
capacity = 10;
arr = new T[capacity];
queueHead = 0;
queueTail = 0;
}

Queue(int cap)
{
if (cap<=0)
{
cout<<"Capacity should be positive! Initialize the queue by default."<<endl;
capacity = 10;
}
else
{
capacity = cap;
}
arr = new T[capacity];
queueHead = 0;
queueTail = 0;
}
~Queue()
{
delete[] arr;
}
};
#endif

 

posted @ 2013-06-08 15:43  肖恩吃青草  阅读(328)  评论(0编辑  收藏  举报