[LeetCode] Implement Queue using Stacks

아르당·2025년 11월 5일

LeetCode

목록 보기
58/68
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

두 개의 스택만 사용해서 선입선출(FIFO)를 구현해라. 구현된 큐는 기본적인 큐의 모든 기능(push, peek, pop, empty)을 지원해야한다.

구현할 MyQueue 클래스

  • void push(int x): 큐의 뒤에 요소 x를 넣어라.
  • int pop(): 큐의 앞에서부터 요소를 제거하고, 반환해라.
  • int peek(): 큐의 앞에 요소를 반환해라.
  • boolean empty(): 큐가 비어있으면 true를, 그렇지 않다면 false를 반환해라.

Example

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]

[[], [1], [2], [], [], []]

Output
[null, null, null, 1, 1, false]

Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); queue is: [1]
myQueue.push(2); queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false;

Constraints

  • 1 <= x <= 9
  • 최대 100개의 push, pop, peek, empty 호출을 한다.
  • pop과 peek에 대한 모든 호출은 유효하다.

Solved

class MyQueue {

    private Stack<Integer> input;
    private Stack<Integer> output;

    public MyQueue() {
        input = new Stack<>();
        output = new Stack<>();
    }
    
    public void push(int x) {
        input.push(x);
    }
    
    public int pop() {
        peek();
        
        return output.pop();
    }
    
    public int peek() {
        if(output.isEmpty()){
            while(!input.isEmpty()){
                output.push(input.pop());
            }
        }

        return output.peek();
    }
    
    public boolean empty() {
        return input.isEmpty() && output.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */
profile
내 마음대로 코드 작성하는 세상

0개의 댓글