Description:
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Link:
https://leetcode.com/problems/implement-queue-using-stacks/#/description
解题方法:
用两个栈in和out来解决,当调用函数pop()
和peek()
时,当out为空时,把in栈的元素压到out里面去,然后对out进行pop()
和top()
的调用。
Time Complexity:
pop()
和peek()
:O(1)到 O(N)
完整代码:
class MyQueue
{
private:
stack<int> inS;
stack<int> outS;
void inToOut()
{
while(!inS.empty())
{
outS.push(inS.top());
inS.pop();
}
}
public:
/** Push element x to the back of queue. */
void push(int x)
{
inS.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop()
{
if(outS.empty())
inToOut();
int front = outS.top();
outS.pop();
return front;
}
/** Get the front element. */
int peek()
{
if(outS.empty())
inToOut();
return outS.top();
}
/** Returns whether the queue is empty. */
bool empty()
{
return inS.empty() && outS.empty();
}
};
网友评论