使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//使用两个栈实现
class MyQueue {
public:
stack<int> left;
stack<int> right;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
right.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(left.empty())
{
int size = right.size();
for(int i = 0; i<size; i++)
{
int d = right.top();
left.push(d);
right.pop();
}
}
int v =left.top();
left.pop();
return v;
}
/** Get the front element. */
int peek() {
if(left.empty())
{
int size = right.size();
for(int i = 0; i<size; i++)
{
int d = right.top();
left.push(d);
right.pop();
}
}
int v =left.top();
return v;
}
/** Returns whether the queue is empty. */
bool empty() {
return left.empty() && right.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();
*/