225. Implement Stack using Queues

Taesoo Kim·2023년 2월 7일
0

CrackingAlgorithm

목록 보기
21/36

문제링크: https://leetcode.com/problems/implement-stack-using-queues/

스택을 이용한 큐 구현 문제입니다. 앞으로 기본적인 자료구조를 정리 해볼 생각입니다.

Problem

스택을 이용해서 큐의 특성을 구현하는 문제입니다. push, pop, top, empty를 순서대로 구현하면 됩니다.

Approach & Solution

사실 파이썬에는 deque라는 자료구조가 있습니다. 그걸로 쉽게 구현 하면 될것 같습니다.

from collections import deque

class MyStack:

    def __init__(self):
        self.queue = collections.deque()        

    def push(self, x: int) -> None:
        
        return self.queue.insert(0,x)
        
    def pop(self) -> int:
        return self.queue.popleft()

    def top(self) -> int:
        return self.queue[0]
        

    def empty(self) -> bool:
        return len(self.queue) == 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()

기본적인 큐나 스택을 이해하고 있는지가 중요한 문제였습니다.

profile
SailingToTheMoooon

0개의 댓글