VS2005运行通过,如有问题,请各位大牛指正。
/*静态数组实现循环队列:少用一个空间,队尾指针的下一位是队头指针时为满
队头、队尾初始值: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
{
private:
Type data[Max];
int front;
int rear;
public:
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()
{
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>
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
{
return (rear == front);
}
template<class Type>
bool Queue<Type>::IsFullQueue() const
{
return ((rear+1)%Max==front);
}
template<class Type>
void Queue<Type>::destoryQueue()
{
front = 0;
rear =0;
}
template<class Type>
void Queue<Type>::deQueue(Type& NewItem)
{
if (isEmptyQueue())
{
cout<<"栈空"<<endl;
}
else
{
NewItem = data[(front++)%Max];
/*等价于 NewItem = data[front]; front =(front+1)%Max; */
}
}
template<class Type>
void Queue<Type>::enQueue(Type NewItem)
{
if (IsFullQueue())
{
cout<<"栈满!"<<endl;
}
else
{
data[(rear++)%Max]= NewItem;
}
}
template<class Type>
int Queue<Type>::lengthQueue()
{
return ((rear - front + Max)%Max);
}
int main()
{
Queue<char>queue;
Queue<char>queue2;
queue2 = queue;
char a[4] = {'1','2','3','4'};
for (int i=0;i<4;i++)
{
queue2.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;
}