题目:
思路:
设置两个栈。用这两个栈倒腾一下数据就可以了。
代码实现:
class MyQueue {
private:
stack<int> stack[2];
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stack[1].push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int t;
if (!stack[0].empty()){
t = stack[0].top();
stack[0].pop();
}else{
while (!stack[1].empty()){
stack[0].push(stack[1].top());
stack[1].pop();
}
t = stack[0].top();
stack[0].pop();
}
return t;
}
/** Get the front element. */
int peek() {
int t;
if (!stack[0].empty()){
t = stack[0].top();
}else{
while (!stack[1].empty()){
stack[0].push(stack[1].top());
stack[1].pop();
}
t = stack[0].top();
}
return t;
}
/** Returns whether the queue is empty. */
bool empty() {
return stack[0].empty() && stack[1].empty();
}
};
/**
* 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();
*/
discuss:
// 思路:两个栈
class MyQueue {
private:
stack<int> input, output;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
input.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int t = peek(); // 借用peek来检查output是否为空
output.pop();
return t;
}
/** Get the front element. */
int peek() {
if (output.empty())
while (input.size())
output.push(input.top()), input.pop();
return output.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return input.empty() && output.empty();
}
};