使用一个队列完成一个栈

2018-01-25 21:11:02

题目描述:

问题求解:

队列的特点是先进先出,栈的特点是先进后出。如果在push的时候,对队列中的元素进行reverse,那么就可以很容易的进行pop(),top(),empty()等操作。

class MyStack {
    Queue<Integer> queue;

    /** Initialize your data structure here. */
    public MyStack() {
        queue = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        int size = queue.size();
        queue.offer(x);
        while (size-- > 0) {
            queue.offer(queue.poll());
        }
        
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return queue.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }
}
原文地址:https://www.cnblogs.com/hyserendipity/p/8353353.html