栈模拟队列
用栈来模拟队列需要两个栈,一个栈s2用于模拟队首,一个栈s1用以压入元素。
代码如下:
#include<iostream>
using namespace std;
#define MaxSize 100
//栈的常规操作定义
typedef struct{
int data[MaxSize];
int top = -1;
}SqStack;
bool StackEmpty(SqStack S){
return S.top == -1;
}
bool Push(SqStack &S,int x){
if(S.top == MaxSize-1) return false;
S.data[++S.top] = x;
return true;
}
bool Pop(SqStack &S,int& x){
if(S.top == -1) return false;
x = S.data[S.top--];
return true;
}
//模拟队列
bool EnQueue(SqStack& s1,SqStack& s2,int x){
int y; //y用来保存弹栈的值
if(s1.top == MaxSize-1){
/*
栈s1满,栈s2非空,此时s2的栈顶是队列的第一个元素,
因为要保证队首出栈,所以s1的元素不可以通过压入s2中来缓解,
入队失败,返回false。
*/
if(!StackEmpty(s2)) return false;
else{
//栈s1满,s2非空,此时将s1元素压入s2中,队首即s2栈顶.
while(!StackEmpty(s1)){
Pop(s1,y);
Push(s2,y);
}
//x进栈
Push(s1,x);
return true;
}
}else{
//s1不满直接压入s1
Push(s1,x);
return true;
}
}
bool DeQueue(SqStack& s1,SqStack& s2,int& x){
int y;
//s2非空,直接弹栈
if(!StackEmpty(s2)){
Pop(s2,x);
return true;
}else{ //s2空,如果s1也空,没有可出队元素,返回false
if(StackEmpty(s1)) return false;
else{ //s2空,s1非空,把s1元素压入s2中,栈顶即队首
while(!StackEmpty(s1)){
Pop(s1,y);
Push(s2,y);
}
//弹出x
Pop(s2,x);
return true;
}
}
}
bool QueueEmpty(SqStack s1,SqStack s2){
//s1,s2都空,即为队空
if(StackEmpty(s1) && StackEmpty(s2)) return true;
else return false;
}
int main(){
SqStack s1,s2;
EnQueue(s1,s2,1);
EnQueue(s1,s2,2);
cout<<QueueEmpty(s1,s2)<<endl;
int x = 0;
DeQueue(s1,s2,x);
cout<<x<<endl;
DeQueue(s1,s2,x);
cout<<x<<endl;
cout<<QueueEmpty(s1,s2);
}
队列模拟栈
队列来模拟栈仅需要一个队列,每进入一个元素把队列内已有元素全部出队再入队就可以了。
代码贴上:
#include<iostream>
using namespace std;
#define MaxSize 100
//队列的常规操作定义
typedef struct{
int data[MaxSize];
int front = 0,rear = 0;
}SqQueue;
bool QueueFull(SqQueue Q){
return (Q.rear + 1)% MaxSize == Q.front;
}
bool QueueEmpty(SqQueue Q){
return Q.front == Q.rear;
}
bool EnQueue(SqQueue &Q,int x){
if(QueueFull(Q)) return false;
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1)% MaxSize;
return true;
}
bool DeQueue(SqQueue &Q,int& x){
if(QueueEmpty(Q)) return false;
x = Q.data[Q.front];
Q.front = (Q.front + 1)% MaxSize;
return true;
}
int QueueSize(SqQueue Q){
return (Q.rear - Q.front + MaxSize)% MaxSize;
}
//模拟栈
bool Push(SqQueue& q,int x){
int y;
if(QueueFull(q)) return false;
EnQueue(q,x);
for(int i = 0;i < QueueSize(q)-1;i++){
DeQueue(q,y);
EnQueue(q,y);
}
return true;
}
bool Pop(SqQueue& q,int& x){
if(QueueEmpty(q)) return false;
DeQueue(q,x);
return true;
}
bool StackEmpty(SqQueue q){
return QueueEmpty(q);
}
int main(){
SqQueue q;
Push(q,1);
Push(q,2);
cout<<StackEmpty(q)<<endl;
int x = 0;
Pop(q,x);
cout<<x<<endl;
Pop(q,x);
cout<<x<<endl;
cout<<StackEmpty(q);
}