*Java* how do you think about this one, good or bad?

  • 1

    I don't see this solution, so here it is.

    Idea: use one stack to store all elements in reversed order. So whenever push an item, reverse current stack and push new item into a temporary stack, afterwards, reverse the temporary stack and save it into the original stack.

    class MyQueue {
    Deque<Integer> stack = new ArrayDeque<>();
    public void push(int x) {
        Deque<Integer> temp = new ArrayDeque<>();
        while(!stack.isEmpty()) {
        while(!temp.isEmpty()) {
    // Removes the element from in front of queue.
    public void pop() {
    // Get the front element.
    public int peek() {
        return stack.peek();
    // Return whether the queue is empty.
    public boolean empty() {
        return stack.isEmpty();

    If you are interested in my other posts, please feel free to check my Github page here: https://github.com/F-L-A-G/Algorithms-in-Java

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.