算法基础(四):队列基础--循环队列

来源:互联网 发布:su软件 编辑:程序博客网 时间:2024/06/06 02:00

直接上代码:

#include "stdafx.h"#include<stdio.h>#include<malloc.h>#include<stdlib.h>#define TRUE  1 #define FALSE 0#define OK    1#define ERROR 0#define INFEASIBLE -1#define OVERFLOW   -2#define MAX_SIZE   6typedef int Status;//函数返回值typedef int QElemType;//暂定元素类型为int,可以根据自己需要修改typedef struct{QElemType *base;//初始化的动态分配存储空间int length;//队列中元素个数int front;int rear;//定义队尾指针}ForQueue; Status InitQueue(ForQueue &Q);//构造一个空队列Status InsertQueue(ForQueue &Q,QElemType e);//插入元素e为Q的队尾元素Status DeQueue(ForQueue &Q);//在队列不为空的情况下,删除队头元素//入口测试函数int _tmain(int argc, _TCHAR* argv[]){ ForQueue Q;if(InitQueue(Q)){ for(int i = 0;i<MAX_SIZE; i++)//0~9自然数入队{if(InsertQueue(Q,i))printf("\n入队成功:%d",i);else printf("\n入队失败:%d",i);}printf("\n元素入队完毕...测试...");for(int i = 0;i<MAX_SIZE;i++) { printf("\n出队元素为:%d",DeQueue(Q)); }}return 0;}Status InitQueue(ForQueue &Q)//构造一个空队列{Q.base = (QElemType *)malloc(MAX_SIZE * sizeof(QElemType));//分配空间,指针指向该空间的首地址if(!Q.base)exit(OVERFLOW);Q.front = Q.rear = 0;Q.length = 0;//初始长度为0return OK;}  Status InsertQueue(ForQueue &Q,QElemType e)//插入元素e为Q的队尾元素{if(Q.length == MAX_SIZE)//表明满了return ERROR; Q.base[Q.rear] = e;Q.rear = (Q.rear + 1) % MAX_SIZE;Q.length++;return OK;}QElemType DeQueue(ForQueue &Q )//在队列不为空的情况下,删除队头元素{if(Q.length == 0)return ERROR;else {QElemType e = Q.base[Q.front];Q.front++; Q.length--;return e;}  }


0 0
原创粉丝点击