您的位置:首页 > 理论基础 > 数据结构算法

软件设计师教程 数据结构之循环队列的实现 (C/C++语言)

2012-03-04 23:39 756 查看
#include<stdio.h>

#include<malloc.h>

#define MAXSIZE 100

typedef struct

{

int *base;

int front;

int rear;

}SqQueue;

void Init_SqQueue(SqQueue *q) //初始化循环队列

{

q->base=(int *)malloc (MAXSIZE * sizeof(int));

if (!q->base) printf("error!\n");

q->front=0;

q->rear=0;

}

void EnSqQueue(SqQueue *q,int e) //入队列

{

if ((q->rear+1)%MAXSIZE==q->front)

printf("error!");

q->base[q->rear]=e;

q->rear=(q->rear+1)%MAXSIZE;

}

void DeQueue(SqQueue *q) //出队列

{

if (q->front==q->rear)

printf("error!");

int e=q->base[q->front];

q->front=(q->front+1)%MAXSIZE;

}

void main()

{

SqQueue *q;

q=new SqQueue; // 注意要new循环队列

Init_SqQueue(q); //初始化循环队列

EnSqQueue(q,32); //入队列

EnSqQueue(q,22);

printf("对头指向的元素为:%d\n",q->base[q->front]); //注意q->front,q->rear都是索引号,只有q->base[q->front]才指向对应元素

DeQueue(q); //出队列,删除了32,此时q->front指向22

printf("出对后,对头指向的元素为:%d\n",q->base[q->front]); //输出此时队头指向的元素

}

运行后的结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: