队列的实现

 

#include "stdafx.h"

#include
<string.h>
#include
<ctype.h>
#include
<malloc.h> // malloc()等
#include<limits.h> // INT_MAX等
#include<stdio.h> // EOF(=^Z或F6),NULL
#include<stdlib.h> // atoi()
#include<io.h> // eof()
#include<math.h> // floor(),ceil(),abs()
#include<process.h> // exit()
#include<iostream> // cout,cin
// 函数结果状态代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
// #define OVERFLOW -2 因为在math.h中已定义OVERFLOW的值为3,故去掉此
//
typedef int Status; // Status是函数的类型,其值是函数结果状态代码,如OK等
typedef int Boolean; // Boolean是布尔类型,其值是TRUE或FALSE

// c3-3.h
#define MAXQSIZE 10
typedef
int QElemType;
struct SqQueue
{
QElemType
*base;
int front;
int rear;
};

Status InitQueue(SqQueue
&Q)
{
//构造一个空队列Q
Q.base=(QElemType *)malloc(MAXQSIZE*sizeof(QElemType));
if(!Q.base)//储存分配失败
exit(OVERFLOW);
Q.front
=Q.rear=0;
return OK;
}
Status DestroyQueue(SqQueue
&Q)
{
//销毁队列Q,Q不再存在
if(Q.base)
free(Q.
base);
Q.
base=NULL;
Q.front
=Q.rear=0;
return OK;
}
Status ClearQueue(SqQueue
&Q)
{
//将Q清为空队列
Q.front=Q.rear=0;
return OK;
}
Status QueueEmpty(SqQueue Q)
{
//若队列Q为空队列,则返回TREU,否则返回FALSE
if(Q.front==Q.rear)//队列空的标志
return TRUE;
else
return FALSE;
}
int QueueLength(SqQueue Q)

{
//Q
return(Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}
Status GetHead(SqQueue Q,QElemType
&e)
{
//
if(Q.front==Q.rear)//队列空
return ERROR;
e
=*(Q.base+Q.front);
return OK;
}
Status EnQueue(SqQueue
&Q,QElemType e)
{
if((Q.rear+1)%MAXQSIZE==Q.front)//队列满
return ERROR;
Q.
base[Q.rear]=e;
Q.rear
=(Q.rear+1)%MAXQSIZE;
return OK;
}
Status DeQueue(SqQueue
&Q,QElemType &e)
{
if(Q.front==Q.rear)//队列空
return ERROR;
e
=Q.base[Q.front];
Q.front
=(Q.front+1)%MAXQSIZE;
return OK;
}
Status QueueTraverse(SqQueue Q,
void(*vi)(QElemType)) //传递函数
{
int i;
i
=Q.front;
while(i!=Q.rear)
{
vi(
*(Q.base+i));
i
=(i+1)%MAXQSIZE;
}
printf(
"\n");
return OK;
}

void visit(QElemType i)
{
printf(
"%d\t",i);
}
void main()
{
int i=0,a=0;
QElemType d;
SqQueue Q;
InitQueue(Q);
printf(
"初始化队列后,队列空否?(1:空 0:否)\n");
printf(
"%d",QueueEmpty(Q));
printf(
"\n");
printf(
"请输入整型队列元素,-1为提前结束符:\n");
do
{
scanf(
"%d",&d);
if(d==-1)
break;
i
++;
EnQueue(Q,d);
}
while(i<MAXQSIZE-1);
printf(
"队列长度为:");
printf(
"%d",QueueLength(Q));
printf(
"\n");
printf(
"现在队列空否?(1:空 0:否)");
printf(
"%d",QueueEmpty(Q));
printf(
"\n");
for(i=1;i<=QueueLength(Q);i++)
{
DeQueue(Q,d);
printf(
"删除的元素为:%d",d);
printf(
"请输入待插入的元素:");
scanf(
"%d",&a);
if(a==0)
{
break;
}
EnQueue(Q,a);
}

printf(
"现在队列中的元素为:\n");
QueueTraverse(Q,visit);
printf(
"\n");
GetHead(Q,a);
printf(
"现在对头元素为%d:",a);
printf(
"\n");
ClearQueue(Q);
printf(
"清空队列后,对列空否?(1:空 0:否)");
printf(
"%d",QueueEmpty(Q));
printf(
"\n");
DestroyQueue(Q);
getchar();
getchar();
}

 

posted on 2010-10-26 19:59  几度夕阳红了  阅读(362)  评论(0)    收藏  举报