Implement Stack using Queues

2772 ワード

まだ2つのqueueがして、書いていません
class MyStack {

    public Queue<Integer> q = new LinkedList<Integer>();

    //cc150 , 

    // single queue

    public void push(int x) {

        q.add((int) x);

    }



    // Removes the element on top of the stack.

    public void pop() {

        if(q.isEmpty()) return;

        for(int i=0;i<q.size()-1;i++){

            q.add(q.peek());

            q.poll();

        }

        int re = q.peek();

        q.poll();

    }



    // Get the top element.

    public int top() {

        if(q.size()<=1) return q.peek();

       for(int i=0;i<q.size()-1;i++){

            q.add(q.peek());

            q.poll();

        }

        int re = q.peek();

        q.add(re);

        q.poll();

        return re;

    }



    // Return whether the stack is empty.

    public boolean empty() {

        return q.isEmpty() ;

    }

}