动态数组实现循环队列

来源:互联网 发布:贵阳软件人均工资 编辑:程序博客网 时间:2024/05/18 15:52

 VS2005和Dev均可以运行通过,如有问题,请各位大牛指正。

/*动态数组实现循环队列:少用一个空间,队尾指针的下一位是队头指针时为满队头、队尾初始值:front = rear = 0;队头:总是指向第一个结点队尾:总是指向最后一个结点的下一位队空:front == rear队满:(rear+1)%Max==front入队: data[(rear++)%Max]= NewItem;出队:NewItem = data[(front++)%Max];*/#include <iostream>using namespace std;const int QueueIncreMent=10; template<class Type>class Queue{private:Type* data;int front;int rear;int maxSize;//队列的最大空间public:Queue(int maxSize = 20);~Queue();Queue(const Queue<Type>& otherQueue);Queue<Type> operator=(const Queue<Type>& otherQueue);void initQueue();bool isEmptyQueue() const;bool IsFullQueue() const;;void destoryQueue();void enQueue(Type newItem);void deQueue(Type& newItem);int lengthQueue();};template<class Type>Queue<Type>::Queue(int maxSize)//不能写成maxSize = 20,否则dev通不过{data = new Type[maxSize];front = 0;rear = 0;this->maxSize = maxSize;}template<class Type>Queue<Type>::~Queue(){if (data!=NULL){destoryQueue();}}template<class Type>Queue<Type>::Queue(const Queue<Type>& otherQueue){if (!otherQueue.isEmptyQueue()){front = otherQueue.front;rear = otherQueue.rear;maxSize = otherQueue.maxSize;data = new Type[maxSize];memcpy(data,otherQueue.data,maxSize);}}template<class Type>Queue<Type> Queue<Type>::operator=(const Queue<Type>& otherQueue){if (this != &otherQueue){if (!otherQueue.isEmptyQueue()){if (maxSize!=otherQueue.maxSize){maxSize = otherQueue.maxSize;delete[] data;data = new Type[maxSize];}front = otherQueue.front;rear = otherQueue.rear;memcpy(data,otherQueue.data,maxSize);}}return *this;}template<class Type>void Queue<Type>::initQueue(){destoryQueue();}template<class Type>bool Queue<Type>::isEmptyQueue() const{return (rear == front);}template<class Type>bool Queue<Type>::IsFullQueue() const{return ((rear+1)%maxSize==front);}template<class Type>void Queue<Type>::destoryQueue(){front = 0;rear =0;delete[] data;data = NULL;}template<class Type>void Queue<Type>::deQueue(Type& NewItem){if (isEmptyQueue()){cout<<"栈空"<<endl;}else{NewItem = data[(front++)%maxSize];/*等价于 NewItem = data[front]; front =(front+1)%Max; */}}template<class Type>void Queue<Type>::enQueue(Type NewItem){if (IsFullQueue()){cout<<"栈满!"<<endl;}else{data[(rear++)%maxSize]= NewItem;}}template<class Type>int Queue<Type>::lengthQueue(){return ((rear - front + maxSize)%maxSize); }int main(){Queue<char>queue;char a[4] = {'1','2','3','4'};for (int i=0;i<4;i++){queue.enQueue(a[i]);}Queue<char>queue1;queue1 = queue;char data;for (int i=0;i<4;i++){queue1.deQueue(data);cout<<data<<endl;}system("pause");return 0;}


 

原创粉丝点击