본문 바로가기
코딩테스트/LeetCode

[LeetCode] Implement Stack using Queues(큐를 이용한 스택구현)

by jungmin.park 2023. 10. 19.

https://leetcode.com/problems/implement-stack-using-queues/description/

 

Implement Stack using Queues - LeetCode

Can you solve this real interview question? Implement Stack using Queues - 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

leetcode.com

  • void push(int x)요소 x를 스택의 맨 위로 푸시합니다.
  • int pop()스택 맨 위에 있는 요소를 제거하고 반환합니다.
  • int top()스택의 맨 위에 있는 요소를 반환합니다.
  • boolean empty()true스택이 비어 있으면 반환하고 , false그렇지 않으면 반환합니다.

<리스트 구현>

클래스 생성자 설정

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

 

삽입 기능 구현

def push(self, x):
        self.k.append(x)
        return

 

삭제 기능 구현

def pop(self):
        if self.k:
            return self.k.pop()
        else:
            return

 

맨 위에 있는 요소 반환 구현

def top(self):
        if self.k:
            return self.k[-1]
        else:
            return

 

비어있는지 확인하는 기능 구현

    def empty(self):
            if len(self.k) == 0:
                return True
            else:
                return False