Implement Stack using Queues

还有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() ;
    }
}

 

posted @ 2015-06-12 09:50  世界到处都是小星星  阅读(116)  评论(0编辑  收藏  举报