큐를 이용해 다음 연산을 지원하는 스택을 구현하라.
Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]
Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
Constraints:
class MyQueue {
private:
stack<int> st1, st2;
public:
MyQueue() {
}
void push(int x) {
st1.push(x);
}
int pop() {
int size = st1.size() - 1;
while (size--)
{
st2.push(st1.top());
st1.pop();
}
int popNum = st1.top();
st1.pop();
while (!st2.empty())
{
st1.push(st2.top());
st2.pop();
}
return popNum;
}
int peek() {
int size = st1.size() - 1;
while (size--)
{
st2.push(st1.top());
st1.pop();
}
int frontNum = st1.top();
st2.push(st1.top());
st1.pop();
while (!st2.empty())
{
st1.push(st2.top());
st2.pop();
}
return frontNum;
}
bool empty() {
if (st1.empty()) return true;
else 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();
*/
Runtime 4 ms / Memory 7.1 MB
https://leetcode.com/problems/implement-queue-using-stacks/submissions/925093713/