c++实现两个栈模拟队列和两个队列模拟一个栈(剑指offer第七题(P59-P62))
#include <iostream>
#include <stack>
#include <queue>
#include <bits/stdc++.h>
using namespace std;
class Queue {
public:
void in(const int &k);
int del();
private:
stack<int> sta1;
stack<int> sta2;
};
void Queue::in(const int &k) {
sta1.push(k);
}
int Queue::del(){
if (sta2.empty())
{
while(!sta1.empty())
{
int tem = sta1.top();
sta2.push(tem);
sta1.pop();
}
}
if (sta2.empty()) {
throw runtime_error("no elements to delete!!!");
}
int res = sta2.top();
sta2.pop();
return res;
}
class Stack{
public:
public:
void in(const int &k);
int del();
private:
queue<int> que1;
queue<int> que2;
};
void Stack::in(const int &k) {
que1.push(k);
}
int Stack::del() {
int res;
if (que1.empty())
{
if (que2.empty())
throw runtime_error("no elements to delete !!!");
while(que2.size()>1)
{
int tem = que2.front();
que1.push(tem);
que2.pop();
}
res = que2.front();
que2.pop();
}
else {
while (que1.size()>1)
{
int tem = que1.front();
que2.push(tem);
que1.pop();
}
res = que1.front();
que1.pop();
}
return res;
}
int main() {
Queue test1;
test1.in(3);
test1.in(4);
test1.del();
cout << test1.del() << endl;
Stack test2;
test2.in(3);
test2.in(4);
test2.del();
cout << test2.del() << endl;
return 0;
}