使用栈来实现队列的如下操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
注意:
你只能使用标准的栈操作-- 也就是只有push to top, peek/pop from top, size, 和 is empty 操作是可使用的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque (双端队列)来模拟一个栈,只要你仅使用栈的标准操作就可以。
假设所有操作都是有效的,比如 pop 或者 peek 操作不会作用于一个空队列上。
详见:https://leetcode.com/problems/implement-queue-using-stacks/description/
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stkPush.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(stkPop.empty())
{
while(!stkPush.empty())
{
stkPop.push(stkPush.top());
stkPush.pop();
}
}
int val=stkPop.top();
stkPop.pop();
return val;
}
/** Get the front element. */
int peek() {
if(stkPop.empty())
{
while(!stkPush.empty())
{
stkPop.push(stkPush.top());
stkPush.pop();
}
}
return stkPop.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return stkPush.empty()&&stkPop.empty();
}
private:
stack<int> stkPush;
stack<int> stkPop;
};
/**
* 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();
*/
232 Implement Queue using Stacks 用栈来实现队列
原文:https://www.cnblogs.com/xidian2014/p/8758959.html