恒邪

环形队中实现队列的基本运算

/*队空条件:front=rear
队满条件:(rear+1)%MaxSize=front
进队e操作:rear=(rear+1)%MaxSize; 将e放在rear处
出队操作:front=(front+1)%MaxSize;取出front处元素e; */
#include <iostream>
#include <malloc.h>
using namespace std;
const int maxn=4;

typedef struct
{
    int data[maxn];
    int front,rear;
}queue;
//初始化队列
void init(queue *&q)
{
    q=(queue*)malloc(sizeof(queue));
    q->rear=q->front=0;
}
//销毁队列
void destroy(queue *&q)
{
    free(q);
}
//判断队列是否为空
bool empty(queue *&q)
{
    return q->front==q->rear;
}
//进队列
void push(queue *&q,int e)
{
    if((q->rear+1)%maxn==q->front)
    {
        cout<<"队满,无法入队!"<<endl;
        return;
    }
    q->rear=(q->rear+1)%maxn;
    q->data[q->rear]=e;
}
//出队列
void pop(queue *&q)
{
    if(q->front==q->rear)
    {
        cout<<"队空,无元素!"<<endl;
        return ;
    }
    q->front=(q->front+1)%maxn;
}

int main()
{
    queue *q;
    init(q);
    push(q,2);
    push(q,4);
    cout<<empty(q);
    pop(q);
    pop(q);
    cout<<empty(q);
    return 0;
}

posted on 2014-04-02 19:17  恒邪  阅读(341)  评论(0编辑  收藏  举报

导航