/*
2011.09.06
循环队列的实现
*/
#include<iostream>
#include<malloc.h>
using namespace std;
#define MAXQSIZE 5
#define OK 1
#define ERROR 0
#define OVERFLOW 0
typedef int Status;
typedef int QElemType;
typedef struct {
QElemType *base;//初始化的动态分配存储空间
int front;
int rear;
}SqQueue;
Status InitQueue( SqQueue &Q ){
//初始化一个空的循环队列
Q.base = ( QElemType * ) malloc ( MAXQSIZE * sizeof( QElemType ) );
Q.front = Q.rear = 0;
return OK;
}
Status QueueLength( SqQueue Q ){
//返回Q的元素个数,即队列的长度
return ( Q.rear - Q.front + MAXQSIZE ) % MAXQSIZE;
}
Status EnQueue( SqQueue &Q, QElemType e ){//数组最后留了一个空间,易于判断,队列是否为满
//插入元素e为Q的新的队尾元素
cout <<e <<endl;
if( ( Q.rear + 1 ) % MAXQSIZE == Q.front ) return ERROR;//队列满
Q.base[ Q.rear ] = e;
Q.rear = ( Q.rear + 1 ) % MAXQSIZE;
return OK;
}
Status DeQueue( SqQueue &Q, QElemType e ){
//若队列不空,则删除Q的对头元素,用e返回其值,并返回OK
//否则返回ERROR
if( Q.front == Q.rear ) return ERROR;
e = Q.base[ Q.front ];
Q.front = ( Q.front + 1 ) % MAXQSIZE;
return OK;
}
int main()
{
SqQueue queue;
InitQueue( queue );
for( int i = 0; i < 3; i++ ){
EnQueue( queue,i );
}
cout << "队列长度为:"<< QueueLength( queue ) << endl;
for( int i = 0; i < 3; i++){
cout << queue.base[ i ] <<"、";
}
system("pause");
return 0;
}
注意事项:在判断队列为满的时候,特意在数组最后留了一个空间,便于确认队列是否为满?
第二种方法:运用flag标记吧。~