Leetcode225
1.问题描述
2.解决方案
(1)思路:
(2)画图解释:
(3)代码实现:
版本一:两个队列实现栈
class MyStack {
private:
queue<int> q1;
queue<int> q2;
public:
MyStack() {
}
void push(int x) {
if(q1.empty()== true){
q2.push(x);
} else{
q1.push(x);
}
}
int pop() {
if(q1.empty()==true){
while(q2.size()>1){
q1.push(q2.front());
q2.pop();
}
int t=q2.front();
q2.pop();
return t;
} else{
while(q1.size()>1){
q2.push(q1.front());
q1.pop();
}
int t=q1.front();
q1.pop();
return t;
}
}
int top() {
if(q1.empty()==true){
while(q2.size()>1){
q1.push(q2.front());
q2.pop();
}
int t=q2.front();
q1.push(t);
q2.pop();
return t;
} else{
while(q1.size()>1){
q2.push(q1.front());
q1.pop();
}
int t=q1.front();
q2.push(t);
q1.pop();
return t;
}
}
bool empty() {
if(!q1.empty()||!q2.empty()) return false;
else return true;
}
};
版本二:一个队列实现栈
1.其实这道题目就是用一个队列就够了,一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
2.此时在去弹出元素就是栈的顺序了。
class MyStack {
public:
queue<int> que;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int size = que.size();
size--;
while (size--) { // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
que.push(que.front());
que.pop();
}
int result = que.front(); // 此时弹出的元素顺序就是栈的顺序了
que.pop();
return result;
}
/** Get the top element. */
int top() {
return que.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return que.empty();
}
};