一般队列
0.定义队列的基本结构
typedef struct {
ElemType data[Maxsize];
int front, rear;
}SqQueue;
1.初始化队列
void InitQueue(SqQueue& Q)
{
Q.front = Q.rear = 0;
}
2.判断队列空
Status QueueEmpty(SqQueue Q)
{
if (Q.rear == Q.front)
return true;
else
return false;
}
3.入队
Status EnQueue(SqQueue& Q, ElemType x)
{
if (Q.rear == Maxsize)
return false;
Q.data[Q.rear] = x;
Q.rear++;
return true;
}
4.出队
Status DeQueue(SqQueue& Q, ElemType& x)
{
if (Q.front == Q.rear)
return false;
x = Q.data[Q.front];
Q.front++;
return true;
}
顺序队列的完整代码
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 20
typedef int ElemType;
typedef bool Status;
typedef struct {
ElemType data[Maxsize];
int front, rear;
}SqQueue;
void InitQueue(SqQueue& Q)
{
Q.front = Q.rear = 0;
}
Status QueueEmpty(SqQueue Q)
{
if (Q.rear == Q.front)
return true;
else
false;
}
Status EnQueue(SqQueue& Q, ElemType x)
{
if (Q.rear == Maxsize)
return false;
Q.data[Q.rear] = x;
Q.rear++;
return true;
}
Status DeQueue(SqQueue& Q, ElemType& x)
{
if (Q.front == Q.rear)
return false;
x = Q.data[Q.front];
Q.front++;
return true;
}
int main()
{
SqQueue Q;
ElemType x;
InitQueue(Q);
EnQueue(Q, 3);
EnQueue(Q, 6);
EnQueue(Q, 8);
EnQueue(Q, 9);
DeQueue(Q, x);
printf("%d\n", x);
return 0;
}
循环队列
0.定义循环队列的基本结构
typedef struct {
ElemType data[Maxsize];
int front, rear;
}SqQueue;
1.初始化队列
void InitQueue(SqQueue& Q)
{
Q.front = Q.rear = 0;
}
2.判断队列空
Status QueueEmpty(SqQueue Q)
{
if (Q.rear == Q.front)
return true;
else
return false;
}
3.入队
Status EnQueue(SqQueue& Q, ElemType x)
{
if ((Q.rear + 1) % Maxsize == Q.front)
return false;
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1) % Maxsize;
return true;
}
4.出队
Status DeQueue(SqQueue& Q, ElemType& x)
{
if (Q.front == Q.rear)
return false;
x = Q.data[Q.front];
Q.front = (Q.front + 1) % Maxsize;
return true;
}
循环队列的完整代码
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 20
typedef int ElemType;
typedef bool Status;
typedef struct {
ElemType data[Maxsize];
int front, rear;
}SqQueue;
void InitQueue(SqQueue& Q)
{
Q.front = Q.rear = 0;
}
Status QueueEmpty(SqQueue Q)
{
if (Q.rear == Q.front)
return true;
else
return false;
}
Status EnQueue(SqQueue& Q, ElemType x)
{
if ((Q.rear + 1) % Maxsize == Q.front)
return false;
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1) % Maxsize;
return true;
}
Status DeQueue(SqQueue& Q, ElemType& x)
{
if (Q.front == Q.rear)
return false;
x = Q.data[Q.front];
Q.front = (Q.front + 1) % Maxsize;
return true;
}
int main()
{
SqQueue Q;
ElemType x;
InitQueue(Q);
EnQueue(Q, 3);
DeQueue(Q, x);
printf("%d\n", x);
return 0;
}
|