일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 29 | 30 |
Tags
- TypeScript
- dotenv
- loop
- machine learning
- BOJ
- vue.js
- vuetify
- C#
- leetcode
- webpack
- nginx
- bash
- var
- 앙상블
- security
- docker
- scss
- Python
- 보안
- condition
- git
- VUE
- npm
- type
- C++
- AI
- generic
- Clone
- JavaScript
- property
Archives
- Today
- Total
ice rabbit programming
[LeetCode] 225. Implement Stack using Queues 본문
https://leetcode.com/problems/implement-stack-using-queues/description/
이전에 스택으로 큐 구현하기와 유사한데, 큐 두 개를 사용한다는 발상은 똑같지만, 학생 때 취준하면서 스택으로 큐 구현하기는 몇 번 해 봤었는데 거꾸로는 처음한 것 같았다. 로직은 이전과 같이 특이한 점이 없기 때문에, 아래 코드를 보면 이해가 갈 것이다. 다만, queue에서는 top이 아니라 front이다.
class MyStack {
public:
MyStack() {
}
void push(int x) {
while(!mainQueue.empty()) {
subQueue.push(mainQueue.front());
mainQueue.pop();
}
mainQueue.push(x);
while(!subQueue.empty()) {
mainQueue.push(subQueue.front());
subQueue.pop();
}
}
int pop() {
int result = mainQueue.front();
mainQueue.pop();
return result;
}
int top() {
return mainQueue.front();
}
bool empty() {
return mainQueue.empty();
}
queue<int> mainQueue;
queue<int> subQueue;
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
'PS > LeetCode' 카테고리의 다른 글
[LeedCode] 268. Missing Number (0) | 2023.12.27 |
---|---|
[LeetCode] 258. Add Digits (0) | 2022.11.10 |
[LeetCode] 232. Implement Queue Using Stacks (0) | 2022.11.10 |
[LeetCode] 766. toeplitz-matrix (0) | 2022.11.10 |
[LeetCode] 242. Valid Anagram (0) | 2022.10.17 |