“a.h”
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
#define MAXSIZE 10
typedef struct {
ElemType *base;
int front; //不是指针,是整数用来指示顺序表的元素。
int rear;
}Queue;
"b.h"
#include"b.c"
Status InitQueue(Queue *q);
Status DestroyQueue(Queue *q);
Status ClearQueue(Queue *q);
Status QueueEmpty(Queue q);
Status QueueLength(Queue q);
Status GetHead(Queue q,ElemType *e);
Status InsertQueue(Queue *q,ElemType e);
Status DeleteQueue(Queue *q,ElemType *e);
Status QueueTraverse(Queue q,Status(*fun)(ElemType));
"b.c"
#include"a.h"
Status InitQueue(Queue *q)
{
(*q).base=(ElemType*)malloc(MAXSIZE*sizeof(ElemType));
if(!(*q).base)
return ERROR;
(*q).front=(*q).rear=0;
return OK;
}
Status DestroyQueue(Queue *q)
{
if((*q).base)
free((*q).base);
(*q).base=0;
(*q).front=(*q).rear=0;
return OK;
}
Status ClearQueue(Queue *q)
{
(*q).front=(*q).rear=0;
return OK;
}
Status QueueEmpty(Queue q)
{
if(q.front==q.rear)
return TRUE;
else
return FALSE;
}
Status QueueLength(Queue q)
{
return (q.rear-q.front+MAXSIZE)%MAXSIZE;
}
Status GetHead(Queue q,ElemType *e)
{
if(q.front==q.rear)
return ERROR;
else
*e=*(q.base+q.front);
return OK;
}
Status InsertQueue(Queue *q,ElemType e)
{
if(((*q).rear+1)%MAXSIZE==(*q).front)
return ERROR;
*((*q).base+(*q).rear)=e; //队列头指针在尾指针的下一位置即为满,牺牲一个存储空间
(*q).rear=((*q).rear+1)%MAXSIZE;
return OK;
}
Status DeleteQueue(Queue *q,ElemType *e)
{
if((*q).front==(*q).rear)
return ERROR;
*e=(*q).base[(*q).front];
(*q).front=((*q).front+1)%MAXSIZE; //一切的%MAXSIZE 都是为了循环
return OK;
}
Status QueueTraverse(Queue q,Status(*fun)(ElemType))
{
int i=q.front;
printf("队头 ");
while(i!=q.rear){
fun(q.base[i]);
i=(i+1)%MAXSIZE;
}
printf("队尾\n");
return OK;
}
"main.c"
#include"b.h"
Status fun(ElemType e)
{
printf(" %d ",e);
return OK;
}
int main()
{
ElemType e;
int i;
Queue q;
InitQueue(&q);
for(i=0;i<9;i++){
printf("请输入插入元素的值:");
scanf("%d",&e);
InsertQueue(&q,e);
}
QueueTraverse(q,fun);
for(i=0;i<7;i++){
DeleteQueue(&q,&e);
printf("删除的元素为 :%d\n",e);
}
QueueTraverse(q,fun);
printf("队列的长度为 %d\n",QueueLength(q));
for(i=0;i<7;i++){
printf("请输入插入元素的值:");
scanf("%d",&e);
InsertQueue(&q,e);
}
QueueTraverse(q,fun);
printf("队列的长度为 %d\n",QueueLength(q));
if(!QueueEmpty(q))
printf("队列不为空\n");
return OK;
}
下面开始写一两个栈,队列的小的应用算法。