[LeetCode]225. Implement Stack using Queues
题目描述
思路
用队列处理时使用一个变量保存栈顶元素,可以稍微加快速度
另一种方法,在push时直接改变输入顺序
代码
#include <iostream>
#include <queue>
using namespace std;
class MyStack {
public:
MyStack() {
top_value = 0;
};
void push(int x) {
top_value = x;
q.push(x);
}
int pop() {
int res = 0;
if (q.size()){
res = top_value;
queue<int> temp;
while (q.size() > 1) {
temp.push(q.front());
if (q.size() == 2)
top_value = q.front();
q.pop();
}
q.pop();
while (temp.size()) {
q.push(temp.front());
temp.pop();
}
}
return res;
}
int top() {
return top_value;
}
bool empty() {
return q.empty();
}
private:
queue<int> q;
int top_value;
};
/*
方法二
class MyStack {
queue<int> q;
public:
void push(int x) {
q.push(x);
for (int i=1; i<q.size(); i++) {
q.push(q.front());
q.pop();
}
}
int pop() {
int res = q.front();
q.pop();
return res;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
};
*/
int main() {
MyStack obj;
int x = 1;
obj.push(1);
obj.push(2);
int param_2 = obj.pop();
int param_3 = obj.top();
bool param_4 = obj.empty();
cout << param_2 << " " << param_3 << " " << param_4 << endl;
system("pause");
return 0;
}