C++顺序循环队列
CycleStack
//顺序循环队列 #include<iostream> using namespace std; typedef int elemType; const int MAXSIZE = 20; struct Queue { elemType data[MAXSIZE]; int front;//头指针 int rear;//尾指针,若队列不空,指向队列队尾元素的下一个位置 }; //初始化 void InitQueue(Queue *q) { q->front = q->rear = 0; } //求队列元素数 int LengthQueue(Queue *q) { return (q->rear - q->front + MAXSIZE)%MAXSIZE; } //若队列未满,插入元素e为队列新的队尾元素 void EnQueue(Queue *q, elemType e) { if((q->rear+1)%MAXSIZE == q->front) cout<<"出错,队列已满."<<endl; q->data[q->rear] = e; q->rear = (q->rear +1)%MAXSIZE; } //若队列不空,删除队头元素 void DeQueue(Queue *q, elemType *e) { if(q->front == q->rear) cout<<"出错,队列为空."<<endl; *e = q->data[q->front]; q->front = (q->front+1)%MAXSIZE; } //遍历队列 void TraQueue(Queue *q) { if(q->front == q->rear) cout<<"队列为空."<<endl; int num = 1; for(int i=(q->front)%MAXSIZE;i<q->rear;i=(i+1)%MAXSIZE) { cout <<num<<":\t"<<q->data[i]<<endl; } } int main() { Queue q; InitQueue(&q); for(int i=1;i<7;i++) EnQueue(&q,i); int length = LengthQueue(&q); cout <<"队列长度为: "<< length <<endl; TraQueue(&q); cout<<endl; cout<<"删除队头元素后,队列为:"<<endl; elemType x = 0; DeQueue(&q,&x); TraQueue(&q); cout<<endl; for(int i=0;i<5;i++) DeQueue(&q,&x); TraQueue(&q); cout<<endl; return 0; }