//error函数用来显示程序错误 error.c
#include "error.h"
void myerror(char *str)
{
switch(errno)
{
case -1:
printf("%s:输入的参数错误\n",str);
break;
case FULL_ERROR:
printf("%s:满队状态\n",str);
break;
case EMPTY_ERROR:
printf("%s:空队状态\n",str);
break;
}
}
char* mystrerror(int num)
{
switch (errno)
{
case ERROR:
return "输入参数错误";
case FULL_ERROR:
return "满队状态";
case EMPTY_ERROR:
return "空队状态";
}
}
//以下是error函数头文件 error.h
#ifndef _ERROR_H
#define _ERROR_H
#include <stdio.h>
#define ERROR -1
#define FULL_ERROR -2
#define EMPTY_ERROR -3
int errno; //错误号
void myerror(char *str);
char *mystrerror(int num);
#endif //_ERROR_H
//列队的创建与主要操作函数声明 queue.h
#include <stdio.h>
#include "queue.h"
#ifndef _queue_h_
#define _queue_h_
#include "error.h"
#define true 1
#define false 0
#define SIZE 10
typedef int queuedata;
typedef struct _queue
{
queuedata data[SIZE];
int front;//指向对头下标
int rear; //指向队尾下标
}queue;
//置空队
int initqueue(queue *q) ;
//进队
int pushqueue (queue *q, queuedata x);
//出队
int dequeue (queue *q, queuedata *x) ;
//判队空否
int queueempty (queue *q);
//判队满否
int queuefull (queue *q);
//取队头
int getfront(queue *q, queuedata *x);
#endif
//函数源代码 queue.c
#include "queue.h"
int initqueue(queue *q) //置空队
{
if(q == NULL)
{
errno = ERROR;
return false;
}
q->front = 0;
q->rear = 0;
return true;
}
int queuefull (queue *q) //判断列队是否是满的
{
if(q == NULL)
{
errno = FULL_ERROR ;
return false;
}
return q->front == (q->rear + 1) % SIZE;
}
int queueempty (queue *q) //判断列队是否是空的
{
if(q == NULL)
{
errno = EMPTY_ERROR;
return false;
}
return q->front == q->rear;
}
int pushqueue (queue *q, queuedata x) //进队
{
if(q == NULL)
{
errno = ERROR;
return false;
}
if(queuefull(q))
{
errno = FULL_ERROR;
return false;
}
q->rear = (q->rear + 1) % SIZE;
q->data[q->rear] = x;
return true;
}
int dequeue (queue *q, queuedata *x) //出队
{
if(q == NULL)
{
errno = ERROR;
return false;
}
if(queueempty(q))
{
errno = EMPTY_ERROR;
return false;
}
q->front = (q->front + 1) % SIZE;
*x = q->data[q->front];
return true;
}
int getfront(queue *q, queuedata *x) //取队头
{
if(q == NULL)
{
errno = ERROR;
return false;
}
if(queueempty(q))
{
errno =EMPTY_ERROR;
return false;
}
int index;
index = (q->front + 1) % SIZE;
*x = q->data[index];
return true;
}
//主函数 maic.c
int main()
{
queue q;
initqueue(&q);
if(queueempty(&q))
{
printf("空队\n");
}
int i;
char str[50];
for(i = 0;i < 10;i++)
{
if(pushqueue(&q,i) != true) //进队失败
{
sprintf(str,"第%d个元素入队失败",i);
myerror(str);
}
}
int x;
for(i = 0;i < 10;i++)
{
if(dequeue(&q,&x) != true) //出队失败
{
sprintf(str,"第%d个元素出队失败",i);
myerror(str);
}
printf("x = %d\n",x);
}
return 0;
}