题目描述:
In this assignment, you need to complete Class Stack’s declaration and definition with Template. The different thing is that the Stack is implemented by two queues.
And you need to define a print function to print the content in the Stack from top to bottom. The format is: every element is followed by a blank space and an endl in the end.
大概意思就是要你利用两个队列实现一个栈的功能。
大概思路有两个:
思路一:
1、进栈:先把元素push进空的队列,如果两者都是空的,则随意。
2、在把另一个非空的队列里面的元素一个个按顺序拿出来,push到前者中。
3、这样就变成后者是空的了,可以用来装下一个进栈的元素。
4、出栈:直接将那个非空的队列里面的元素front()出来再pop()掉就可以。
思路二:
1、进栈:把元素push进非空的队列,如果两者都是空的,则随意。
2、出栈:把非空队列里面的前n-1个元素push到空队列里面,再把最后一个元素拿出来即可。
3、循环以上步骤,即可得到实现目的。
分析:虽然两个思路在理论上都行得通,但是第一个思路的时间复杂度太高,实现效率不高,所以下面贴出来的是第二个思路的代码:
#include "queue"
#include "iostream"
using namespace std;
template <typename T>
class Stack {
public:
Stack() {
count = 0;
}
~Stack() {}
void push(const T & data) {
if (!q2.empty()) {
q2.push(data);
} else {
q1.push(data);
}
count&#