아래와 같은 queue의 동작을 두개의 stack만 이용해서 구현하라. stack은 push/pop/top/size/empty 메소드를 사용할 수 있다.
Implement the MyQueue class:
void push(int x) Pushes element x to the back of the queue.
int pop() Removes the element from the front of the queue and returns it.
int peek() Returns the element at the front of the queue.
boolean empty() Returns true if the queue is empty, false otherwise.
class MyQueue {
public:
stack<int> first, second;
MyQueue() {
}
void push(int x) {
first.push(x);
}
int pop() {
while (first.size()) {
second.push(first.top());
first.pop();
}
int ret = second.top();
second.pop();
while (second.size()) {
first.push(second.top());
second.pop();
}
return ret;
}
int peek() {
while (first.size()) {
second.push(first.top());
first.pop();
}
int ret = second.top();
while (second.size()) {
first.push(second.top());
second.pop();
}
return ret;
}
bool empty() {
if (first.size() == 0)
return true;
return false;
}
};
/**
* 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();
*/