99클럽 코테 스터디 5일차 TIL + 스택/큐

개발자 춘식이·2025년 4월 4일
0

항해99클럽

목록 보기
5/10

문제

LeetCode 225-ImplementStackUsingQueues

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.

예시

입력:

["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]

출력:

[null, null, null, 2, 2, false]

풀이

class MyStack {
    Queue<Integer> q1;
    Queue<Integer> q2;

    public MyStack() {
        q1 = new LinkedList<>();
        q2 = new LinkedList<>();
    }
    
    public void push(int x) {
        q2.offer(x);

        while(!q1.isEmpty()) {
            q2.offer(q1.poll());
        }

        Queue<Integer> temp = q1;
        q1 = q2;
        q2 = temp;
    }
    
    public int pop() {
        return q1.poll();
    }
    
    public int top() {
        return q1.peek();
    }

    public boolean empty() {
        return q1.isEmpty();
    }
}

회고

Queue의 기본 메서드들을 잘 봐야겠다..!

profile
춘식이를 너무 좋아하는 주니어 백엔드 개발자입니다.

0개의 댓글