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來解決,當(dāng)調(diào)用函數(shù)pop()和peek()時,當(dāng)out為空時,把in棧的元素壓到out里面去,然后對out進(jìn)行pop()和top()的調(diào)用。
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();
}
};