큐를 이용해 다음 연산을 지원하는 스택을 구현하라.
Input
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 2, 2, false]
Explanation
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False
Constraints:
class MyStack {
private:
queue<int> q1, q2;
public:
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
if (q1.empty()) return -1;
int size = q1.size() - 1;
int endNum = q1.back();
while (size--)
{
q2.push(q1.front());
q1.pop();
}
q1.pop();
while (!q2.empty())
{
q1.push(q2.front());
q2.pop();
}
return endNum;
}
int top() {
if (!q1.empty()) return q1.back();
else return -1;
}
bool empty() {
if (q1.empty()) return true;
else return false;
}
};
Runtime 0 ms / Memory 6.9 MB
https://leetcode.com/problems/implement-stack-using-queues/submissions/925093161/