题目:
1.用队列结构实现栈结构
2.用栈结构实现队列结构
思路:
1.队列->栈:准备两个队列data help
入栈:data入队,help不动
出栈:除了最后一个数据,data的数据依次放入help中,data.pop() 之后help data交换
返回栈顶元素:直接return data的最后一个元素即可
#include<iostream>
#include<queue>
using namespace std;
class QueuetoStack
{
public:
queue<int> data;
queue<int> help;
void push(int a)
{
data.push(a);
}
void pop()
{
for (int i = 0; i < data.size() - 1; i++)
{
help.push(data.front());
data.pop();
}
data.pop();
data.swap(help);
}
int top()
{
return data.back();
}
};
int main()
{
QueuetoStack myStack;
myStack.push(5);
myStack.push(3);
myStack.push(8);
cout << myStack.top() << endl;
myStack.pop();
cout << myStack.top() << endl;
}
2.栈->队列:准备两个栈a和b
入列:往a中push即可
出列:将a全部倒入b(记住保证a的栈底是要出列的元素)b一定要弹干净才能从a倒
#include<iostream>
#include<stack>
using namespace std;
class StacktoQueue
{
public:
stack<int> stack1;
stack<int> stack2;
void push(int a)
{
stack1.push(a);
}
void pop()
{
if (stack2.empty())
{
for (int i = 0; i < stack1.size()-1; i++)
{
stack2.push(stack1.top());
stack1.pop();
}
stack2.pop();
}
else stack2.pop();
}
};