C语言之数组队列

时间:2020-12-21 04:44:11
//主函数头文件
#ifndef __SQQUEUE_H__
#define __SQQUEUE_H__
#include "error.h"

#define SIZE 10
#define TRUE 1
#define FLASE 0

typedef struct _queue
{
int data[SIZE];
int front;
int rear;

}Queue;

int EnQueue (Queue *q, int x); //进队
int DeQueue (Queue *q, int *x);//出队
int GetFront (Queue *q, int *x);//取队头
void InitQueue (Queue *q); //置空队
int QueueEmpty (Queue *q); //判队空否
int QueueFull (Queue *q); //判队满否

#endif

//错误信息处理头文件
#ifndef __ERROR_H__
#define __ERROR_H__

#include <stdio.h>
#define ERROR -1
#define FULL_STACK -2
#define EMPTY_STACK -3
#define MALLOC_STACK -4
#define QUEUEFULL -5
#define QUEUEEMPTY -6

int errno;

void myerror(char *str);

char *mysrterror (int num);

#endif //__ERROR_H__

//错误信息处理
#include "error.h"

void myerror(char *str)
{
printf("%s:%s\n",str,mysrterror(errno));
}

char *mysrterror(int num)
{
switch(num)
{
case ERROR:
return "输入参数错误";

case FULL_STACK:
return "满栈";

case EMPTY_STACK:
return "空栈";

case MALLOC_STACK:
return "空间分配失败";
case QUEUEFULL:
return "队满状态";
case QUEUEEMPTY:
return "队空状态";
}
}

//主要代码
#include "sqQueue.h"
#include <stdlib.h>

void InitQueue (Queue *q)
{
if(q ==NULL)
{
errno = ERROR;
return;
}

q->front = 0;
q->rear = 0;
}

int QueueEmpty (Queue *q)
{
if(q == NULL)
{
errno = ERROR;
return FLASE;
}

return q->front == q->rear;
}

int QueueFull (Queue *q)
{
if(q == NULL)
{
errno = ERROR;
return TRUE;
}
return q->front == (q->rear+1)%SIZE;
}

int EnQueue (Queue *q, int x)
{
if(q == NULL)
{
errno = ERROR;
return FLASE;
}
if(QueueFull(q))
{
errno = QUEUEFULL;
return FLASE;
}

q->rear = (q->rear + 1) % SIZE;
q->data[q->rear] = x;

return TRUE;
}

int DeQueue (Queue *q, int *x)
{
if(q == NULL)
{
errno = ERROR;
return FLASE;
}
if(QueueEmpty(q))
{
errno = QUEUEEMPTY;
return FLASE;
}
q->front = (q->front + 1) % SIZE;
*x = q->data[q->front];

return TRUE;
}

int GetFront (Queue *q, int *x)
{
if(q == NULL)
{
errno = ERROR;
return FLASE;
}
if(QueueEmpty(q))
{
errno = QUEUEEMPTY;
return FLASE;
}
int index = (q->front + 1) % SIZE;
*x = q->data[index];

return TRUE;
}

//主函数
#include "sqQueue.h"
#include <stdio.h>

int main()
{
Queue q;
int i;
char ch[50];
int x = 0;

InitQueue(&q);

if (QueueEmpty(&q))
{
printf ("空队\n");
}

for(i = 0;i < 10;i++)
{
if (EnQueue(&q, i) != TRUE)
{
sprintf (ch, "第 %d 个元素入队失败", i);
myerror(ch);
}
}

for (i = 0; i < 10; i++)
{
if (DeQueue(&q, &x) != TRUE)
{
sprintf (ch, "第 %d 个元素出队失败", i);
myerror(ch);
}

printf ("x = %d\n", x);

return 0;
}

}