일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- vue.js
- machine learning
- loop
- type
- dotenv
- 앙상블
- leetcode
- VUE
- git
- bash
- security
- C++
- var
- AI
- BOJ
- scss
- Clone
- 보안
- C#
- Python
- webpack
- vuetify
- property
- docker
- condition
- JavaScript
- npm
- generic
- nginx
- TypeScript
Archives
- Today
- Total
ice rabbit programming
[LeetCode] 232. Implement Queue Using Stacks 본문
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
'PS > LeetCode' 카테고리의 다른 글
[LeetCode] 258. Add Digits (0) | 2022.11.10 |
---|---|
[LeetCode] 225. Implement Stack using Queues (0) | 2022.11.10 |
[LeetCode] 766. toeplitz-matrix (0) | 2022.11.10 |
[LeetCode] 242. Valid Anagram (0) | 2022.10.17 |
[LeetCode] 231. Power of Two (0) | 2020.12.08 |