这一章是关于循环的代码实现。 循环队列的数据结构:
typedef struct {
ElemType data[MaxSize];
int front,rear;
}SqQueue;
主要函数如下:
- bool EnQueue(SqQueue& Q, ElemType e) 功能:入队;
参数:Q:队列, e:入队的元素; 时间复杂度:O(1); - bool DeQueue(SqQueue& Q, ElemType& e) 功能:出队,出队的元素赋值给e;
参数:Q:队列, e:出队的元素; 时间复杂度:O(1); - void PrintQueue(SqQueue Q) 功能:从队首到队尾输出所有元素;
参数:Q:栈; 时间复杂度:O(n);
#include<cstdio>
#include<cstdlib>
#include<iostream>
#define ElemType int
#define MaxSize 50
typedef struct {
ElemType data[MaxSize];
int front,rear;
}SqQueue;
void InitQueue(SqQueue& Q) {
Q.front = Q.rear = 0;
}
bool isEmpty(SqQueue Q) {
if (Q.rear == Q.front)
return true;
else
return false;
}
bool isFull(SqQueue Q) {
if ((Q.rear + 1) % MaxSize == Q.front)
return true;
else
return false;
}
bool EnQueue(SqQueue& Q, ElemType e) {
if (isFull(Q))
return false;
Q.data[Q.rear] = e;
Q.rear = (Q.rear + 1) % MaxSize;
return true;
}
bool DeQueue(SqQueue& Q, ElemType& e) {
if (isEmpty(Q))
return false;
e = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return true;
}
void PrintQueue(SqQueue Q) {
if (isEmpty(Q))
printf("队空\n");
else {
int n = (Q.rear - Q.front + MaxSize) % MaxSize;
printf("队首->队尾:\n");
while (Q.front != Q.rear) {
printf("%d ", Q.data[Q.front]);
Q.front = (Q.front + 1) % MaxSize;
}
printf("\n共有%d个元素\n", n);
}
}
void CreateQueue(SqQueue& Q) {
InitQueue(Q);
int n;
ElemType e;
while (true) {
printf("输入创建的队列的元素个数:\n");
scanf("%d", &n);
if (n > 50)
printf("元素个数不能大于50,重新输入!\n");
else
break;
}
printf("按序输入队列的元素:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &e);
EnQueue(Q, e);
}
}
void Enter(SqQueue& Q) {
ElemType e;
printf("输入要入队的元素:\n");
scanf("%d", &e);
if (EnQueue(Q, e))
printf("入队成功!\n");
else
printf("入队失败!\n");
}
void Delete(SqQueue& Q) {
ElemType e;
if (DeQueue(Q, e))
printf("%d出队成功!\n", e);
else
printf("出队失败!\n");
}
void menu() {
printf("\n\n");
printf("----------①创建队列----------\n");
printf("----------② 入队 ----------\n");
printf("----------③ 出队 ----------\n");
printf("----------④打印队列----------\n");
printf("按“0”退出\n");
printf("\n\n");
}
int main() {
SqQueue Q;
int choice;
do
{
menu();
scanf("%d", &choice);
switch (choice)
{
case(1):
CreateQueue(Q);
break;
case(2):
Enter(Q);
break;
case(3):
Delete(Q);
break;
case(4):
PrintQueue(Q);
break;
default:
break;
}
} while (choice != 0);
return 0;
}
|