0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Leetcode 232. Implement Queue using Stacks

Posted at

難易度

Easy

アプローチ

Stack

class MyQueue {

    public  Stack<Integer> mainStack;
    public  Stack<Integer> subStack;

    public MyQueue() {
        mainStack = new Stack<>();
        subStack = new Stack<>();

    }

    public void push(int x) {
        mainStack.add(x);
    }

    public int pop() {
        while(!mainStack.empty()){
            subStack.add(mainStack.pop());
        }

        int result = subStack.pop();

        mainStack = new Stack<>();
        while(!subStack.empty()){
            mainStack.add(subStack.pop());
        }

        subStack = new Stack<>();
        return result;
    }

    public int peek() {
        while(!mainStack.empty()){
            subStack.add(mainStack.pop());
        }

        int result = subStack.peek();

        mainStack = new Stack<>();
        while(!subStack.empty()){
            mainStack.add(subStack.pop());
        }

        subStack = new Stack<>();
        return result;
    }

    public boolean empty() {
        return mainStack.empty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?