Algorithm

Make Queue with 2 stack in Java

ByteBridge 2024. 4. 6. 19:43
반응형
import java.util.Stack;

public class QueueByStack {
    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
    }
    
    static class MyQueue {
        Stack<Integer> s1;
        Stack<Integer> s2;
        
        public MyQueue() {
            s1 = new Stack<>();
            s2 = new Stack<>();
        }
        
        public void offer(int x) {
            s1.push(x);
        }
        
        public int poll() {
            if (s2.isEmpty()) {
                while (!s1.isEmpty()) {
                    s2.push(s1.pop());
                }
            }
            return s2.pop();
        }
        
        public int peek() {
            if (s2.isEmpty()) {
                while (!s1.isEmpty()) {
                    s2.push(s1.pop());
                }
            }
            return s2.peek();
        }
        
        public boolean empty() {
            return s1.isEmpty() && s2.isEmpty();
        }
    }
}
반응형