函数说明😃:
InitStack( &s):初始化栈
StackEmpty(s):判断一个栈是否为空
Push(& s, x):进栈
Pop(&s, &x):出栈
GetTop(s,&x):读栈顶元素
show(s):读出目前栈中的元素
代码😃:
constexpr auto maxsize = 10;
#include<stdio.h>
typedef struct {
int data[maxsize];
int front, rear;
}SqQueue;
void initQueue(SqQueue& Q) {
Q.front = Q.rear = 0;
printf("初始化成功\n");
}
bool isEmpty(SqQueue Q) {
if (Q.front == Q.rear)return true;
else return false;
}
bool EnQueue(SqQueue &Q,int x) {
if ((Q.rear + 1) % maxsize == Q.front)return false;
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1) % maxsize;
return true;
}
bool DeQueue(SqQueue & Q) {
if (Q.rear == Q.front)return false;
Q.front = (Q.front + 1) % maxsize;
return true;
}
int QueueLength(SqQueue Q) {
if (Q.rear == Q.front)return 0;
int length;
length = (Q.rear - Q.front + maxsize) % maxsize;
return length;
}
void Queueshow(SqQueue Q){
printf("目前队中的元素为");
int i = Q.front, h = Q.rear;
for (i; i != h; i = (i + 1) % maxsize) {
printf("%d\t", Q.data[i]);
}
printf("\n");
}
bool QueueGetHead(SqQueue Q,int &x) {
if (Q.rear == Q.front)return false;
x = Q.data[Q.front];
return true;
}
int main() {
SqQueue Q;
int i,e;
while (true)
{
printf("*****************************************\n");
printf("请输入您要进行的操作:\n");
printf("1.初始化队 2.入队\n");
printf("3.判断队空 4.出队\n");
printf("5.求队的长度 6.目前队中的元素 7.读队头元素\n");
printf("*****************************************\n");
scanf_s("%d", &i);
switch (i)
{
case 1:initQueue(Q);
break;
case 2:printf("请输入你要输入的元素");
scanf_s("%d", &e);
EnQueue(Q, e);
break;
case 3:if (isEmpty(Q)) {
printf("队列为空\n");
}
else
{
printf("队列不为空\n");
}
break;
case 4:DeQueue(Q); break;
case 5: e = QueueLength(Q);
printf("队的长度为%d\n", e);
break;
case 6:Queueshow(Q);
break;
case 7:QueueGetHead(Q, e);
printf("队头元素为%d\n",e);
break;
default:
break;
}
}
return 0;
}
效果展示😃: