PS/LeetCode
[LeetCode] 232. Implement Queue Using Stacks
판교토끼
2022. 11. 10. 20:15
728x90
https://leetcode.com/problems/implement-queue-using-stacks/description/
Implement Queue using Stacks - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
주니어 코테나 면접에서 상당히 자주 등장하는, 스택으로 큐 구현하기이다. 스택 두 개를 활용하면 어렵지 않게 구현할 수 있다. 로직 자체는 어렵지 않으니 아래 코드를 보면 이해가 갈 것이다. 문제 자체도 제네릭(템플릿)한 것이 아니라 int에 한정되어 있어 간편했다.
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
if(mainStack.empty()) {
mainStack.push(x);
} else {
while(!mainStack.empty()) {
subStack.push(mainStack.top());
mainStack.pop();
}
mainStack.push(x);
while(!subStack.empty()) {
mainStack.push(subStack.top());
subStack.pop();
}
}
}
int pop() {
int result = mainStack.top();
mainStack.pop();
return result;
}
int peek() {
return mainStack.top();
}
bool empty() {
return mainStack.empty();
}
stack<int> mainStack;
stack<int> subStack;
};
/**
* 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();
*/
728x90