<LeetCode 문제>
https://leetcode.com/problems/implement-queue-using-stacks/
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
<풀이>
input과 output 두 개의 스택을 이용해서 queue를 구현합니다.
output 스택에 아무것도 없는 상태에서 pop을 수행하려고 할 때 input 스택에 쌓여있는 값들을 전부 output 스택으로 이관시키는 것이 포인트입니다!
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() #output 비어있으면 input꺼 옮기기
return self.output.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if not self.output: #output이 비어있으면
while self.input:
self.output.append(self.input.pop()) #output으로 다 옮기기
return self.output[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return len(self.input)==0 or len(self.output)==0 #input, 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()
<학습내용>
1.
<학습이 필요한 내용>
1. pop, peek 차이
'Algorithm > 파이썬 알고리즘 인터뷰 스터디' 카테고리의 다른 글
| [데크, 우선순위 큐] 26 원형 데크 디자인(Design Circular Deque) (0) | 2021.08.21 |
|---|---|
| [스택, 큐] 25 원형 큐 디자인(Design Circular Queue) - 작성중 (0) | 2021.08.16 |
| [스택, 큐] 23 큐를 이용한 스택 구현(Implement Stack using Queues) - 작성중 (0) | 2021.08.16 |
| [스택, 큐] 22 일일 온도(Daily Temperatures) - 작성중 (0) | 2021.08.16 |
| [스택, 큐] 21 중복 문자 제거(Remove Duplicate Letters) - 작성중 (0) | 2021.08.16 |