1. 문제
https://leetcode.com/problems/implement-stack-using-queues/
Implement Stack using Queues - 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
2. 접근 방법
queue로 stackd의 push, pop, top, empty를 구현하는 문제입니다.
그래서 deque를 사용했습니다.
pop, top, empty는 문제될 게 없는데, push가 조금 까다롭습니다.
push는 stack의 top (첫번째)로 넣어줘야하기 때문에,
사실 deque의 appendleft()를 사용해도 되지만 이는 파이썬이 제공하는 스택 연산에 해당하는 것이기 때문에,
큐의 연산인 append만 이용해서 했습니다 ^-^
일단 append를 한 뒤, 앞의 요소들을 모두 popleft한 뒤 다 append해주는 것 ..!
3. 코드
python
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.q = collections.deque()
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.q.append(x)
for _ in range(len(self.q)-1):
self.q.append(self.q.popleft())
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.q.popleft()
def top(self) -> int:
"""
Get the top element.
"""
return self.q[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
return len(self.q) == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
4. 마치며
스택에서 push할 경우 요소가 top으로 간다는 것을 알아버렸습니다 ^-^
자료구조 열심히 공부해야겠네여
'Algorithm > Python' 카테고리의 다른 글
[LeetCode] 200. Number of Islands (0) | 2021.06.07 |
---|---|
[LeetCode] 232. Implement Queue using Stacks (0) | 2021.06.06 |
[LeetCode] 739. Daily Temperatures (0) | 2021.06.06 |
[LeetCode] 20. Valid Parentheses (0) | 2021.06.06 |
[백준 2468] 안전영역 (0) | 2021.06.06 |