题目描述:
解法一(两个队列,压入 -O(1), 弹出 -O(n))
class MyStack {
queue<int> que1;
queue<int> que2;
int Top;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que1.push(x);
Top=x;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int res=Top;
while(que1.size()>1){
Top=que1.front();
que2.push(Top);
que1.pop();
}
que1.pop();
queue<int> temp=que1;
que1=que2;
que2=temp;
return res;
}
/** Get the top element. */
int top() {
return Top;
}
/** Returns whether the stack is empty. */
bool empty() {
return que1.empty();
}
};
/**
* 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();
*/
解法二(两个队列,压入 -O(n), 弹出 -O(1)):
class MyStack {
queue<int> que1;
queue<int> que2;
int Top;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
Top=x;
que2.push(x);
while(!que1.empty()){
que2.push(que1.front());
que1.pop();
}
queue<int> temp=que1;
que1=que2;
que2=temp;
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
if(!que1.empty()){
int res=Top;
que1.pop();
Top=que1.front();
return res;
}
else return -1;
}
/** Get the top element. */
int top() {
return Top;
}
/** Returns whether the stack is empty. */
bool empty() {
return que1.empty();
}
};
/**
* 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();
*/
解法三(两个队列,压入 -O(n), 弹出 -O(1)):
class MyStack {
queue<int> que;
int Top;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
Top=x;
int sz=que.size();
que.push(x);
while(sz--){
que.push(que.front());
que.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
if(!que.empty()){
int res=Top;
que.pop();
Top=que.front();
return res;
}
else return -1;
}
/** Get the top element. */
int top() {
return Top;
}
/** Returns whether the stack is empty. */
bool empty() {
return que.empty();
}
};
/**
* 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();
*/