제목 그대로 stack을 사용하여 queue를 구현하는 문제
단순히 두 개의 stack을 사용하는 방법이 아닌
1개만 사용하는 방법이 있을까하여 생각해봤는데
방법이 떠오르지 않아 다른 사람이 한 걸 참고하였다.
class MyQueue {
public:
stack<int> _stack{};
MyQueue() {
}
void push(int x) {
if (_stack.empty())
{
_stack.push(x);
}
else
{
int temp = _stack.top();
_stack.pop();
push(x);
_stack.push(temp);
}
}
int pop() {
int result{_stack.top()};
_stack.pop();
return result;
}
int peek() {
return _stack.top();
}
bool empty() {
return _stack.empty();
}
};
/**
* 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();
*/