新建一个栈,读取标准输入3个整数3 4 5,入栈3 4 5,依次出栈,打印 5 4 3,新建循环队列(Maxsize为5),读取标准输入3 4 5 6 7,入队7时,队满,打印false,然后依次出队,输出 3 4 5 6
#include <stdio.h>
#include <stdlib.h>
#define maxsize 5
typedef struct {
int data[maxsize];
int top;
} stack;
void initStack(stack &s) {
s.top = -1;
}
bool pushStack(stack &s, int num) {
if (s.top == maxsize - 1) {
return false;
}
s.data[++s.top] = num;
return true;
}
bool deStack(stack &s, int &e) {
if (s.top == -1) {
return false;
}
e = s.data[s.top--];
return true;
}
typedef struct {
int data[maxsize];
int front, rear;
} Queue;
void initQueue(Queue &q) {
q.front = 0;
q.rear = 0;
}
bool isEmpty(Queue q) {
if (q.rear == q.front) { return true; } else { return false; }
}
bool enQueue(Queue &q, int num) {
if ((q.rear + 1) % maxsize == q.front) {
printf("false\n");
return false;
} else {
q.data[q.rear] = num;
//错误写法:q.rear++;
q.rear = (q.rear + 1) % maxsize;//防止超过数组最大下标
return true;
}
}
bool deleteQueue(Queue &q, int &e) {
if (q.rear == q.front) {
return false;
}
e = q.data[q.front];
q.front = (q.front + 1) % maxsize;
return true;
}
int main() {
int e;
int num;
stack s;
Queue q;
initStack(s);
for (int i = 0; i < 3; i++) {
scanf("%d", &num);
pushStack(s, num);
}
for (int i = 0; i < 3; i++) {
deStack(s, e);
printf("%2d", e);
}
printf("\n");
initQueue(q);
isEmpty(q);
bool result;
int num1;
for (int i = 0; i < 5; i++) {
scanf("%d", &num1);
enQueue(q, num1);
}
for (int i = 0; i < 5; i++) {
result = deleteQueue(q, e);
if (result) {
printf("%2d", e);
}
}
}
?