1、用两个栈实现队列
假设为A、B栈(AB栈功能明确)
进栈时,只要让A栈负责压入元素;
出栈时,只从B栈中弹出元素;
如果B栈需要出元素但为空时,需要一次性将A栈元素全部导入到B栈中,再弹出B栈元素。
实现代码如下所示:
#include<vector>
#include<queue>
#include<stack>
#include<iostream>
using namespace std;
template<typename T>
class MyQueue {
public:
T top();
void pop();
void push(T);
private:
stack<T> sta1;//被用来装只出队列元素
stack<T> sta2;//被用来装刚压入队列的元素
};
template<typename T>
T MyQueue<T>::top() {
if (sta1.empty() && sta2.empty())
throw new exception("queue is empty");
if (!sta1.empty())
return sta1.top();
else {
while (!sta2.empty()) {//将sta2的元素全压到sta1中来
sta1.push(sta2.top());
sta2.pop();
}
return sta1.top();
}
}
template<typename T>
void MyQueue<T>::push(T val) {
sta2.push(val);
}
template<typename T>
void MyQueue<T>::pop() {
if (sta1.empty() && sta2.empty())
throw new exception("queue is empty");
if (!sta1.empty())
sta1.pop();
else {
while (!sta2.empty()) {//将sta2的元素全压到sta1中来
sta1.push(sta2.top());
sta2.pop();
}
sta1.pop();
}
}
//测试代码
int main() {
MyQueue<int> q;
q.push(9);
q.push(8);
cout << q.top() << endl;
q.push(5);
q.push(1);
for (int i = 0; i < 4; ++i) {
cout << q.top() << endl;
q.pop();
}
return 0;
}
2、用两个队列实现栈
两个队列存在的状态是一个为空队列,另一个是按栈的顺序装有元素的队列
进栈元素,需要压入到空队列A去,于是将另一队列B元素出队列依次A队列,此时B队列又变成了空队列。
再简述一下:
但凡进栈元素都进入到空队列中,将另一非空队列元素依次出队列再进入到
含有一个元素的队列中。确保了最新元素在队头,此外还确保了始终有一个空队列的存在(用来装新入栈的元素)
实现代码如下所示:
#include<queue>
#include<iostream>
#include<exception>
using namespace std;
template<typename T> class MyStack {
public:
void push(const T& element);
void pop();
T top();
private:
queue<T> que1;
queue<T> que2;
};
/*
进栈元素,需要压入到空队列A去,于是将另一队列B元素出队列依次A队列
再简述一下:
但凡进栈元素都进入到空队列A中,将另一非空队列B元素依次出队列再进入到
A队列中,确保了最新元素在队头,此外还确保了始终有一个空队列的存在
*/
template<typename T> void MyStack<T>::push(const T& element) {
if (que1.empty()) {
que1.push(element);
while (!que2.empty()) {
T tmp = que2.front();
que1.push(tmp);
que2.pop();
}
}
else {
que2.push(element);
while (!que1.empty()) {
T tmp = que1.front();
que2.push(tmp);
que1.pop();
}
}
}
template<typename T>
void MyStack<T>::pop() {
if (!que1.empty()) {
que1.pop();
return;
}
else if (!que2.empty()) {
que2.pop();
return;
}
throw exception("This stack has no element.");
}
template<typename T> T MyStack<T>::top() {
if (!que1.empty()) {
T tmp = que1.front();
return tmp;
}
else if (!que2.empty()) {
T tmp = que2.front();
return tmp;
}
throw exception("This stack has no element.");
}
/*
验证功能代码
*/
int main() {
MyStack<int> sta;
sta.push(1);
cout << sta.top() << endl;
sta.push(2);
cout << sta.top() << endl;
sta.pop();
cout << sta.top() << endl;
return 0;
}