본문 바로가기
Portpolio/java_algo_interview

자바 알고리즘 인터뷰 09. 스택, 큐

by Peter Choi 2023. 12. 31.
반응형

[ch9/P23] L225. 큐를 이용한 스택 구현

import java.util.LinkedList;
import java.util.Queue;

public class P23 {

    private Queue<Integer> queue1;
    private Queue<Integer> queue2;

    public P23() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        queue1.offer(x);
    }

    public int pop() {
        while (queue1.size() > 1) {
            queue2.offer(queue1.poll());
        }
        int topElement = queue1.poll();
        swapQueues();
        return topElement;
    }

    public int top() {
        while (queue1.size() > 1) {
            queue2.offer(queue1.poll());
        }
        int topElement = queue1.peek();
        queue2.offer(queue1.poll());
        swapQueues();
        return topElement;
    }

    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }

    public void swapQueues() {
        Queue<Integer> tmp = queue1;
        queue1 = queue2;
        queue2 = tmp;
    }

    public static void main(String[] args) {
        P23 myStack = new P23();
        myStack.push(1);
        myStack.push(2);
        System.out.println(myStack.top()); // Output: 2
        System.out.println(myStack.pop()); // Output: 2
        System.out.println(myStack.empty()); // Output: false
    }

}

 

 

[ch9/P24] L232. 스택을 이용한 큐 구현

import java.util.Stack;

public class P24 {
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;

    public P24() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    public void push(int x) {
        stack1.push(x);
    }

    public int pop() {
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

    public int peek() {
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.peek();
    }

    public boolean empty() {
        return stack1.isEmpty() && stack2.isEmpty();
    }

    public static void main(String[] args) {
        P24 myQueue = new P24();
        myQueue.push(1);
        myQueue.push(2);
        System.out.println(myQueue.peek()); // Output: 1
        System.out.println(myQueue.pop()); // Output: 1
        System.out.println(myQueue.empty()); // Output: false
    }
}
반응형

댓글