队列的顺序存储结构及其基本运算的实现

代码:

#include <iostream>
#include <malloc.h>
using namespace std;
const int maxn=500;

typedef struct
{
    int data[maxn];
    int front,rear;
}queue;

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


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


 

posted @ 2014-04-02 18:56  同学少年  阅读(280)  评论(0编辑  收藏  举报