TIL🔥/코딩테스트

[항해99클럽] Java 비기너_Day 5 Implement Stack using Queues

hk713 2025. 4. 4. 17:47

오늘의 문제 >> Implement Stack using Queues - LeetCode

 

[ 생각 흐름 ]

어제는 스택으로 큐를 구현헀고, 오늘은 큐로 스택을 구현하는거니

단순히 큐랑 스택만 바꿔치기 하면 되는게 아닐까 싶었다

 

[ Java ] - 오답

class MyStack {
    private Queue<Integer> oldQueue;
    private Queue<Integer> newQueue;

    public MyStack() {
        oldQueue = new LinkedList<>();
        newQueue = new LinkedList<>();
    }
    
    public void push(int x) {
        oldQueue.offer(x);
    }
    
    public int pop() {
        if(newQueue.isEmpty()){
            while(!oldQueue.isEmpty()){
                newQueue.offer(oldQueue.poll());
            }
        }
        return newQueue.poll();
    }
    
    public int top() {
        if(newQueue.isEmpty()){
            while(!oldQueue.isEmpty()){
                newQueue.offer(oldQueue.poll());
            }
        }
        return newQueue.peek();
        
    }
    
    public boolean empty() {
        return oldQueue.isEmpty() && newQueue.isEmpty();
    }
}

처음 내 생각과는 다르게 틀렸다..!

 

결국 해결한 코드는 아래와 같다.

[ Java ]

class MyStack {
    private Queue<Integer> oldQueue;
    private Queue<Integer> newQueue;

    public MyStack() {
        oldQueue = new LinkedList<>();
        newQueue = new LinkedList<>();
    }
    
    public void push(int x) {
        oldQueue.offer(x);
    }
    
    public int pop() {
        while(oldQueue.size()>1){
            newQueue.offer(oldQueue.poll());
        }
        int topElement = oldQueue.poll();
        
        Queue<Integer> temp = oldQueue;
        oldQueue = newQueue;
        newQueue = temp;

        return topElement;
    }
    
    public int top() {
        while(oldQueue.size()>1){
            newQueue.offer(oldQueue.poll());
        }
        int topElement = oldQueue.peek();
        
        newQueue.offer(oldQueue.poll());
        Queue<Integer> temp = oldQueue;
        oldQueue = newQueue;
        newQueue = temp;

        return topElement;
    }
    
    public boolean empty() {
        return oldQueue.isEmpty();
    }
}