实现的功能
void InitQueue(Queue& Q); //初始化队列
bool QueueEmpty(Queue Q); //判断队空
bool EnQueue(Queue& Q, int x); //入队
bool DeQueue(Queue& Q, int& x); //出队
顺序实现
完整代码:
/*
Name:SqQueue(循环队列顺序表实现)
Copyright:
Author: Sdjzu_Nxy
Date: 2023 年 2 月 28 日
Description:
*/
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 10
typedef struct {
int data[MaxSize];
int front, rear;
} SqQueue;
void InitQueue(SqQueue& Q); //初始化队列
bool QueueEmpty(SqQueue Q); //判断队空
bool EnQueue(SqQueue& Q, int x); //入队
bool DeQueue(SqQueue& Q, int& x); //出队
void InitQueue(SqQueue& Q)
{
Q.front = Q.rear = 0;
}
bool QueueEmpty(SqQueue Q)
{
return Q.front == Q.rear ? true : false;
}
bool EnQueue(SqQueue& Q, int x)
{
if (Q.front == (Q.rear + 1) % MaxSize) {
return false;
}
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1) % MaxSize;
return true;
}
bool DeQueue(SqQueue& Q, int& 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;
InitQueue(Q);
printf("The SqQueue is empty? %d\n", QueueEmpty(Q));
if (!EnQueue(Q, 1)) {
printf("The SqQueue is full!\n");
}
if (!EnQueue(Q, 2)) {
printf("The SqQueue is full!\n");
}
if (!EnQueue(Q, 3)) {
printf("The SqQueue is full!\n");
}
int x;
printf("The DeQueue is ");
while (DeQueue(Q, x)) {
printf("%d ", x);
}
printf("\nThe SqQueue is empty? %d\n", QueueEmpty(Q));
}
运行结果:
链式实现
完整代码:
/*
Name:LinkQueue(链队实现)
Copyright:
Author: Sdjzu_Nxy
Date: 2023 年 2 月 28 日
Description:
*/
#include<stdio.h>
#include<stdlib.h>
typedef struct LinkNode {
int data;
struct LinkNode *next;
};
typedef struct {
LinkNode* front, * rear;
} LinkQueue;
void InitQueue(LinkQueue& Q); //初始化队列
bool QueueEmpty(LinkQueue Q); //判断队空
bool EnQueue(LinkQueue& Q, int x); //入队
bool DeQueue(LinkQueue& Q, int& x); //出队
void InitQueue(LinkQueue& Q)
{
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
bool QueueEmpty(LinkQueue Q)
{
return Q.front == Q.rear ? true : false;
}
bool EnQueue(LinkQueue& Q, int x)
{
LinkNode* q = (LinkNode*)malloc(sizeof(LinkNode));
if (q == NULL)
{
return false;
}
q->data = x;
q->next = Q.rear->next;
Q.rear->next = q;
Q.rear = q;
return true;
}
bool DeQueue(LinkQueue& Q, int& x)
{
if (Q.front == Q.rear) {
return false;
}
LinkNode* q = Q.front->next;
x = q->data;
Q.front->next = q->next;
if (Q.rear == q) {
Q.rear = Q.front;
}
free(q);
return true;
}
int main() {
LinkQueue Q;
InitQueue(Q);
printf("The SqQueue is empty? %d\n", QueueEmpty(Q));
if (!EnQueue(Q, 1)) {
printf("The SqQueue is full!\n");
}
if (!EnQueue(Q, 2)) {
printf("The SqQueue is full!\n");
}
if (!EnQueue(Q, 3)) {
printf("The SqQueue is full!\n");
}
int x;
printf("The DeQueue is ");
while (DeQueue(Q, x)) {
printf("%d ", x);
}
printf("\nThe SqQueue is empty? %d\n", QueueEmpty(Q));
}
运行结果: