栈是先进后出,队列是先进先出操作,用两个栈可以实现队列操作。先把数据压入其中一个栈,栈顶元素最后进入,然后在把栈里元素压入另外一个栈,则原来栈顶元素变为栈底元素,原来栈底元素变为栈顶元素,然后对第二个栈弹出操作,则弹出的就是最先进入第一个栈的元素了,这就实现了队列操作,先进先出。
#include<iostream>
using namespace std;
struct stack{
int data[5];
int top;
}s1,s2;
struct queue{
int data[5];
int tail;
int first;
}q;
int main(){
s1.top=0;
s2.top=0;
q.first=q.tail=0;
//往栈1输入数据和队列输入数据
for(int i = 0; i < 5; i++){
cin>>s1.data[s1.top];
q.data[q.tail]=s1.data[s1.top];
q.tail++;
s1.top++;
}
//栈1数据弹出至栈2
while(s1.top > 0){
s1.top--;
s2.data[s2.top] = s1.data[s1.top];
s2.top++;
}
//栈2数据弹出
while(s2.top > 0){
s2.top--;
cout<<s2.data[s2.top]<<endl;
}
//队列操作
while(q.first<q.tail){
cout<<q.data[q.first]<<" ";
q.first++;
}
cout<<endl;
return 0;
}