首页 > 编程语言 > 详细

C++顺序循环队列

时间:2015-10-06 22:05:46      阅读:416      评论:0      收藏:0      [点我收藏+]

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;
}

 

C++顺序循环队列

原文:http://www.cnblogs.com/jx-yangbo/p/4857724.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!