LeetCode - 225. Implement Stack using Queues (Python)

조민수·2024년 6월 5일
0

LeetCode

목록 보기
17/61

Easy, Queue, Stack

RunTime : 27 ms / Memory : 16.52 MB


문제

Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).

Implement the MyStack class:

  • void push(int x) Pushes element x to the top of the stack.
  • int pop() Removes the element on the top of the stack and returns it.
  • int top() Returns the element on the top of the stack.
  • boolean empty() Returns true if the stack is empty, false otherwise.

Notes:

  • You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
  • Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.

풀이

  • 처음에 이게 뭔 소린지 했는데 단순하게 Stack의 기능을 Queue로 구현하라는거였다.
    • 아니 이걸 왜...?
from collections import deque
class MyStack:
    def __init__(self):
        self.q = deque()

    def push(self, x: int) -> None:
        self.q.append(x)
        for _ in range(len(self.q) - 1):
            self.q.rotate(-1)

    def pop(self) -> int:
        return self.q.popleft()
        

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

    def empty(self) -> bool:
        if self.q:
            return False
        else:
            return True

그냥 stack을 구현해도 풀리긴 한다.

class MyStack:
    def __init__(self):
        self.st = []

    def push(self, x: int) -> None:
        self.st.append(x)

    def pop(self) -> int:
        return self.st.pop()
        

    def top(self) -> int:
        return self.st[-1]

    def empty(self) -> bool:
        if self.st:
            return False
        else:
            return True
profile
사람을 좋아하는 Front-End 개발자

0개의 댓글