NowCoder LeetCode
题目描述
用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。
解题思路
in 栈用来处理入栈(push)操作,out 栈用来处理出栈(pop)操作。一个元素进入 in 栈之后,出栈的顺序被反转。当元素要出栈时,需要先进入 out 栈,此时元素出栈顺序再一次被反转,因此出栈顺序就和最开始入栈顺序是相同的,先进入的元素先退出,这就是队列的顺序。
参考答案
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int tmp;
if(stack2.empty()) {
while(!stack1.empty()) {
tmp = stack1.top();
stack2.push(tmp);
stack1.pop();
}
}
tmp = stack2.top();
if(!stack2.empty()) stack2.pop();
return tmp;
}
private:
stack<int> stack1;
stack<int> stack2;
};
LeetCode 232 答案
class MyQueue {
private:
stack<int> in, out;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
in.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int tmp;
if(out.empty()) {
while(!in.empty()) {
tmp = in.top();
out.push(tmp);
in.pop();
}
}
tmp = out.top();
if(!out.empty()) out.pop();
return tmp;
}
/** Get the front element. */
int peek() {
int tmp;
if(out.empty()) {
while(!in.empty()) {
tmp = in.top();
out.push(tmp);
in.pop();
}
}
tmp = out.top();
//if(!out.empty()) out.pop();
return tmp;
}
/** Returns whether the queue is empty. */
bool empty() {
if(out.empty() && in.empty()) return true;
return false;
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/