目录
预定义类型
Typedef.h文件,定义了一些类型
//Typedef.h
#pragma once
//
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
//
typedef int Status;
typedef int ElemType;
队列的静态顺序存储结构
Queue.h文件,定义了队列的静态顺序存储结构,以及声明了一些基本操作
//Queue.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include"Typedef.h"
//顺序存储结构的队列
#define MAXSIZE 100
typedef struct SqQueue{
ElemType data[MAXSIZE];
int front, rear;
#if 1
int size;
int tag;
#endif // 1
}SqQueue;
Status InitQueue(SqQueue& Q);
Status EnQueue(SqQueue& Q, ElemType e);
Status DeQueue(SqQueue& Q, ElemType& e);
Status Empty(SqQueue Q);
Status Full(SqQueue Q);
int GetLength(SqQueue Q);
void testQueue();
Queue.cpp文件,实现了Queue.h中声明的函数,讨论了队尾指针不同指向时判空判满的条件
//Queue.cpp
#include"Queue.h"
Status InitQueue(SqQueue& Q)
{
#if 1
//队尾指针rear指向队尾元素的下一个
Q.front = Q.rear = 0;
#if 1
Q.size = 0; //标识队列当前长度
Q.tag = 0; //标识最近一次操作是入队还是出队
#endif // 0
return Status();
#endif // 1
#if 0
//队尾指针rear指向队尾元素
Q.front = 0;
Q.front = MAXSIZE - 1;
#endif // 0
}
Status EnQueue(SqQueue& Q, ElemType e)
{
#if 1
//如果只有front,rear
if (Full(Q))
return OVERFLOW;
else {
Q.data[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXSIZE;
}
return OK;
#endif // 1
#if 0
//如果还有size和tag
Q.size++;
Q.tag = 1;
#endif // 0
}
Status DeQueue(SqQueue& Q, ElemType& e)
{
#if 1
if (Empty(Q))
return ERROR;
else {
e = Q.data[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;
}
return OK;
#endif // 1
#if 0
//如果还有size和tag
Q.size--;
Q.tag = 0;
#endif // 0
}
Status Empty(SqQueue Q)
{
#if 1
//如果只有front,rear
if (Q.front == Q.rear)
return TRUE;
else
return FALSE;
#endif // 1
#if 0
//如果有front,rear,size
if(size==0)
return TRUE;
else
return FALSE;
#endif // 0
#if 0
//如果有front,rear,tag
if (Q.tag == 0 && Q.front == Q.rear)
return TRUE;
else
return FALSE;
#endif // 0
}
Status Full(SqQueue Q)
{
#if 1
//如果只有front,rear
//此时会损失一个位置,有效位置为MAXSIZE-1
if ((Q.rear + 1) % MAXSIZE == Q.front)
return TRUE;
else
return FALSE;
#endif // 1
#if 0
//如果有front,rear,size,有效位置MAXSIZE
if (size == MAXSIZE)
return TRUE;
else
return FALSE;
#endif // 0
#if 0
//如果有front,rear,tag,有效位置MAXSIZE
if (Q.front==Q.rear&&Q.tag==1)
return TRUE;
else
return FALSE;
#endif // 0
}
int GetLength(SqQueue Q)
{
#if 1
//如果没有size
int length = 0;
length = ((Q.rear + MAXSIZE) - Q.front) % MAXSIZE;
return length;
#endif // 1
#if 0
return Q.size;
#endif // 0
}
void testQueue()
{
SqQueue Q;
InitQueue(Q);
ElemType e = 0;
for (int i = 0; i < 11; i++) {
int f = EnQueue(Q, i);
if (f)
printf("%d ", i);
}
printf("\n");
while (!Empty(Q)){
DeQueue(Q, e);
printf("%d ", e);
}
}