232. Implement Queue using Stacks

kukudas·2022년 3월 21일
0

Algorithm

목록 보기
23/46
class MyQueue:

    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def push(self, x):
        self.stack1.append(x)

    def pop(self):
        # 뺴기전에 역순으로 한번 옮겨줌
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())

        return self.stack2.pop()

    def peek(self):
        # 여기서 다른 스택으로 다 옮겨줌
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())

        return self.stack2[-1]

    def empty(self):
        return not self.stack1 and not self.stack2

https://leetcode.com/problems/implement-queue-using-stacks/

0개의 댓글

관련 채용 정보