#include <stdio.h> #include <stdlib.h> #define MaxSize 5 typedef int ElemType; typedef struct { ElemType data[MaxSize];//数组 int top;//始终指向栈顶的变量 } SqStack; typedef struct { ElemType data[MaxSize];//数组 int front, rear;//始终指向栈顶的变量 } SqQueue; //初始化栈 void InitStack(SqStack &S) { S.top = -1;//代表栈为空 } //入栈 bool Push(SqStack &S, ElemType x) { if (S.top == MaxSize - 1) { return false; } S.data[++S.top] = x;//S.top=S.top+1; S.data[S.dop]=x return true; } //出栈 bool Pop(SqStack &S, ElemType &x) { if (-1 == S.top) return false; x = S.data[S.top--]; return true; } //初始化队列 void InitQueue(SqQueue Q) { Q.front = Q.rear; } //判断对列是否为空 bool isEmpty(SqQueue &Q) { if (Q.rear == Q.front) return true; else return false; } //循环入队 bool 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;//防止rear大于数组最大下标。 return true; } //出队 bool DeQueue(SqQueue &Q, ElemType &x) { if (Q.rear == Q.front) { return false; } x = Q.data[Q.front];//出队,先进先出 Q.front = (Q.front + 1) % MaxSize; return true; } int main() { int element; SqStack S; ElemType m; InitStack(S); for (int i = 0; i < 3; i++) { scanf("%d\n", &element); Push(S, element);//入栈 } //出栈 for (int i = 0; i < 3; i++) { Pop(S, m); printf("%2d", m); } printf("\n"); SqQueue Q; bool flag; InitQueue(Q); for (int i = 0; i < 5; i++) { scanf("%d", &element); flag = EnQueue(Q, element); if (false == flag) { printf("false\n"); } } ElemType num; for (int i = 0; i < 4; i++) { DeQueue(Q, num); printf("%2d", num); } printf("\n"); return 0; }
新建一个栈,读取标准输入3个整数3 4 5,入栈3 4 5,依次出栈,打印 5 4 3,新建循环队列(Maxsize为5),读取标准输入3 4 5 6 7,入队7时,队满,打印false,然后依次出队
于 2024-05-14 19:00:09 首次发布