Programming/LeetCode

[LeetCode] #232. Implement Queue using Stacks

dev.pudding 2024. 2. 5. 13:12
728x90
class MyQueue {
     
     private Stack<Integer> stack1;
     private Stack<Integer> stack2;

    public MyQueue() {
       stack1 = new Stack<>();
       stack2 = new Stack<>();
    }
    
    //enqueue (FIFO)
    public void push(int x) {
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }

        stack1.push(x);
        while(!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }

    }
    
    //dequeue (FIFO)
    public int pop() {
        if(empty()){
            return 0;
        }else{
            return stack1.pop();
        }
    }
    
    public int peek() {
       return stack1.peek();
    }
    
    public boolean empty() {
        return stack1.isEmpty();
    }
}

https://leetcode.com/problems/implement-queue-using-stacks/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com