Use two stacks. Every time I need to pop, I push all numbers in st1 into st2 except the last one, then I pop that one. After that, I push back all numbers into st1. Don't forget to update the front variable.
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
if(st1.empty())
front=x;
st1.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
while(st1.size()!=1)
{
st2.push(st1.top());
st1.pop();
}
st1.pop();
if(!st2.empty())
front=st2.top();
while(!st2.empty())
{
st1.push(st2.top());
st2.pop();
}
}
// Get the front element.
int peek(void) {
return front;
}
// Return whether the queue is empty.
bool empty(void) {
return st1.empty();
}
private:
stack<int> st1;
stack<int> st2;
int front;
};