문제 출처 : leetcode.com/problems/implement-queue-using-stacks/
문제 해석 : Stack을 이용해서 Queue를 구현 하는 문제이다.
문제 풀이 : 다른 기능들은 쉽게 구현 할 수 있지만 pop을 수행 할때는 순서에 유의해서 temp 배열에 저장하고 원하는 값을 꺼낸뒤에 다시 원상태로 복귀 시켜줘야 한다.
풀이 코드
class MyQueue:
def __init__(self):
self.Q = []
def push(self, x: int) -> None:
self.Q.append(x)
def pop(self) -> int:
temp = []
while len(self.Q) > 1:
temp.append(self.Q.pop())
ret = self.Q.pop()
while temp:
self.Q.append(temp.pop())
return ret
def peek(self) -> int:
return self.Q[0]
def empty(self) -> bool:
if len(self.Q) == 0:
return True
else:
return False
author : donghak park
contact : donghark03@naver.com
## 문제의 저작권은 LeetCode 사이트에 있습니다. 혹시 문제가 되는 부분이 있으면 연락 바랍니다.
'📊알고리즘, 문제풀이 > 📈문제풀이 (PS)' 카테고리의 다른 글
[알고리즘][Python] LeetCode 771 Jewels and Stones 문제 풀이 (0) | 2021.02.27 |
---|---|
[알고리즘][Python] LeetCode 622 Design Circular Queue 문제 풀이 (0) | 2021.02.25 |
[알고리즘][Python] LeetCode 225 Implement Stack Using Queues 문제 풀이 (0) | 2021.02.25 |
[알고리즘][Python] 백준 17940 지하철 문제 풀이 (0) | 2021.02.24 |
[알고리즘][Python] LeetCode 20 Valid Parentheses 문제 풀이 (0) | 2021.02.23 |