225. Implement Stack using Queues

来源:互联网 发布:网络营销策划方案 论文 编辑:程序博客网 时间:2024/05/16 03:17
class MyStack {
    Queue<Integer> q = new LinkedList<Integer>();


    // Push element x onto stack.
    public void push(int x) {
        q.add(x);
    }


    // Removes the element on top of the stack.
    public void pop() {
        int size = q.size();
        for(int i = 1; i < size; i++)
            q.add(q.remove());
        q.remove();
    }


    // Get the top element.
    public int top() {
        int size = q.size();
        for(int i = 1; i < size; i++)
            q.add(q.remove());
        int ret = q.remove();
        q.add(ret);
        return ret;
    }


    // Return whether the stack is empty.
    public boolean empty() {
        return q.isEmpty();        
    }
}
0 0
原创粉丝点击