#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#define Max 10
//q是队列,s是栈,实现q中元素逆置
typedef struct {
int data[Max];
int f, r, tag;
}squeue;
typedef struct {
int data[Max];
int top;
}stack;
bool enter(squeue& s, int x) {//入队
if (s.r == s.f && s.tag == 1) {
printf("队列已满");
return false;
}
s.data[s.r] = x;
s.r = (s.r + 1) % Max;
s.tag = 1;
return true;
}
bool quit(squeue& s, int& x) {//出队
if (s.r == s.f && s.tag == 0) {
printf("队列已空");
return 0;
}
x = s.data[s.f];
s.f = (s.f + 1) % Max;
s.tag = 0;
return 1;
}
bool push(stack& s,int x){//入栈
if (s.top==Max-1) {
printf("manle");
return false;
}
s.data[++s.top] = x;
return true;
}
bool pop(stack& s, int &x) {//出栈
if (s.top == - 1) {
printf("kongle");
return 0;
}
x = s.data[s.top--];
return 1;
}
void disp(squeue s) {
for (int i = 0; i < Max; i++) {
printf("%3d", s.data[s.f]);
s.f = (s.f + 1) % Max;
}return;
}
int main() {
squeue s1;
stack s2;
s1.f = 0, s1.r = 0, s1.tag = 0;
s2.top = -1;
for (int i=0;i<Max;i++) {
enter(s1,i);
}
disp(s1);
int x = 0;
while (!(s1.r == s1.f && s1.tag == 0)) {
quit(s1, x);
push(s2, x);
}
while (!(s2.top == -1)) {
pop(s2, x);
enter(s1, x);
}
disp(s1);
return 0;
}
0307q是队列,s是栈,实现q中元素逆置
于 2022-11-10 18:28:16 首次发布
这段代码展示了如何利用栈来实现队列中元素的逆置。定义了两个结构体,一个表示队列,一个表示栈,分别实现了入队、出队、入栈和出栈操作。在主函数中,首先将队列填满,然后依次将队列元素出队并入栈,最后再从栈中弹出元素并重新入队,从而达到队列元素逆置的效果。
摘要由CSDN通过智能技术生成