题目描述
用队列实现栈
参考代码
相似题目:[LeetCode] 232、用栈实现队列,简单题。
bool g_invalidInput = false;
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
// nothing
}
/** Push element x onto stack. */
void push(int x) {
if(!q1.empty())
q1.push(x);
else
q2.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
if(!q1.empty()){
int num = q1.size();
while(num != 1){
q2.push(q1.front());
q1.pop();
num--;
}
int res = q1.front();
q1.pop();
return res;
}else{
int num = q2.size();
while(num != 1){
q1.push(q2.front());
q2.pop();
num--;
}
int res = q2.front();
q2.pop();
return res;
}
g_invalidInput = true;
return -1;
}
/** Get the top element. */
int top() {
if(!q1.empty()){
int num = q1.size();
while(num != 1){
q2.push(q1.front());
q1.pop();
num--;
}
int res = q1.front();
q2.push(res);
q1.pop();
return res;
}else{
int num = q2.size();
while(num != 1){
q1.push(q2.front());
q2.pop();
num--;
}
int res = q2.front();
q1.push(res);
q2.pop();
return res;
}
g_invalidInput = true;
return -1;
}
/** Returns whether the stack is empty. */
bool empty() {
if(q1.empty() && q2.empty())
return true;
else
return false;
}
private:
queue<int> q1, q2;
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
来源:CSDN
作者:aift
链接:https://blog.csdn.net/ft_sunshine/article/details/104064161