1. 문제
https://leetcode.com/problems/implement-queue-using-stacks/
2. 접근 방법
이번에는 stack을 이용해 queue의 push, pop, peek, empty를 구현하는 것임다
stack은 후입선출인데, queue는 선입선출이라
push는 append로 구현하면 되는데,
pop, peek을 위해 맨 앞의 요소에 접근해야합니다.
그래서 어쩔 수 없이 2개를 사용해야해용
그래서 input, output이라는 배열을 만들어서
스택의 pop과 append를 사용해서 요리저리 움직여보았ㅅ브니다.
약간 하노이탑같아요 하하
3. 코드
python
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.input = []
self.output = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.input.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
self.peek()
return self.output.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if not self.output:
while self.input:
self.output.append(self.input.pop())
return self.output[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return self.input == [] and self.output == []
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
4. 마치며
그래두 직접 구현해보니까 또 느낌이 다르네요
'Algorithm > Python' 카테고리의 다른 글
[LeetCode] 39. Combination Sum (0) | 2021.06.07 |
---|---|
[LeetCode] 200. Number of Islands (0) | 2021.06.07 |
[LeetCode] 225. Implement Stack using Queues (0) | 2021.06.06 |
[LeetCode] 739. Daily Temperatures (0) | 2021.06.06 |
[LeetCode] 20. Valid Parentheses (0) | 2021.06.06 |