Implement Stack using Queues

题目地址

class MyStack {
    // Push element x onto stack.
  Queue<Integer> queueA=new ArrayDeque<Integer>();
    Queue<Integer> queueB=new ArrayDeque<Integer>();


    boolean Aflag=true;

    public void push(int x) {
        if(Aflag)
        {
            queueA.add(x);
        }
        else
        {
            queueB.add(x);
        }
    }

    // Removes the element on top of the stack.
    public void pop() {
        if(Aflag)
        {
            while(queueA.size()>1)
            {
                queueB.add(queueA.remove());
            }
            queueA.remove();
            Aflag=false;
        }
        else
        {
            while(queueB.size()>1)
            {
                queueA.add(queueB.remove());
            }
            queueB.remove();
            Aflag=true;
        }
    }

    // Get the top element.
    public int top() {
        int temp=0;
        if(Aflag)
        {
            while(queueA.size()>1)
            {
                queueB.add(queueA.remove());
            }
            temp=queueA.remove();
            Aflag=false;
        }
        else
        {
            while(queueB.size()>1)
            {
                queueA.add(queueB.remove());
            }
            temp=queueB.remove();
            Aflag=true;
        }
        push(temp);
        return temp;
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return Aflag?queueA.isEmpty():queueB.isEmpty();
    }
}

你可能感兴趣的:(Implement Stack using Queues)