用棧實現隊列(C++)
準備兩個棧 instack,outstack
入隊時,push到instack棧中
出隊時:
1.如果outstack爲空,把instack棧中元素每一個push到outstack,並從instack中彈出,出隊列即彈出outstack的棧頂元素
2.如果outstack不爲空,彈出outstack棧頂元素
class MyQueue {
private:
void checkoutStack()
{
if (outstack.empty()) //爲空
{
while (!instack.empty())
{
outstack.push(instack.top());
instack.pop();
}
}
}
public:
stack<int> instack;
stack<int> outstack;
/** Initialize your data structure here. */
MyQueue()
{
}
/** Push element x to the back of queue. */
void push(int x)
{
instack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
checkoutStack();
int tmp = outstack.top();
outstack.pop();
return tmp;
}
/** Get the front element. */
int peek()
{
checkoutStack();
return outstack.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return instack.empty() && outstack.empty();
}
};