静态数组实现循环队列

来源:互联网 发布:卡通农场最新数据 编辑:程序博客网 时间:2024/05/17 23:58

vs2008运行正确,如有误,请各位大牛指正!

// SQueue.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"/*静态数组实现循环队列:少用一个空间,队尾指针的下一位是队头指针时为满队头、队尾初始值:front = rear = 0;队头:总是指向第一个结点队尾:总是指向最后一个结点的下一位队空:front == rear队满:(rear+1)%Max==front入队: data[(rear++)%Max]= NewItem;出队:NewItem = data[(front++)%Max];*/#include <iostream>using namespace std;const int Max = 50;template<class Type>class Queue{public:Queue();Queue(const Queue<Type>& otherQueue);const 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();private:Type data[Max];int front;int rear;};template<class Type>Queue<Type>::Queue(){front = 0;rear = 0;}template<class Type>Queue<Type>::Queue(const Queue<Type>& otherQueue){front = otherQueue.front;rear = otherQueue.rear;if (!otherQueue.isEmptyQueue()){memcpy(data,otherQueue.data,Max);}}template<class Type>const Queue<Type>& Queue<Type>::operator=(const Queue<Type>& otherQueue){if (this!=&otherQueue){if (!otherQueue.isEmptyQueue()){front = otherQueue.front;rear = otherQueue.rear;memcpy(data,otherQueue.data,Max);}}return *this;}template<class Type>void Queue<Type>::initQueue(){front = 0;rear = 0;}template<class Type>bool Queue<Type>::isEmptyQueue() const{if (front == rear){return true;}else{return false;}}template<class Type>bool Queue<Type>::IsFullQueue() const{if ((rear+1)%Max == front){return true;}else{return false;}}template<class Type>void Queue<Type>::destoryQueue(){front = 0;rear = 0;}template<class Type>void Queue<Type>::enQueue(Type newItem){if (IsFullQueue()){cout<<"队列满!"<<endl;}else{data[(rear++)%Max] = newItem;}}template<class Type>void Queue<Type>::deQueue(Type& newItem){if (isEmptyQueue()){cout<<"队列空!"<<endl;}else{newItem = data[(front++)%Max];}}template<class Type>int Queue<Type>::lengthQueue(){return ((rear-front+Max)%Max);}int _tmain(int argc, _TCHAR* argv[]){Queue<char> queue1;Queue<char> queue2;char a[4] = {'1','2','3','4'};for (int i=0; i<4; i++){queue1.enQueue(a[i]);}queue2 = queue1;    Queue<char> queue3(queue2);for (int i=0; i<4; i++){char b;queue3.deQueue(b);cout<<b<<" ";}cout<<endl;system("pause");return 0;}