1. 程式人生 > >佇列實現一個棧

佇列實現一個棧

當插入一個元素時,要實現後進元素先出,需要把該元素之前的元素先出佇列,重新進入佇列的尾部。此時就實現了後進先出

佇列插入

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) {
        queue.add(x);
        int size=queue.size();
        while(size-->1){
            //插入元素前面的元素先出來,在進入佇列
            queue.add(queue.poll());
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.remove();
    }
    
    /** Get the top element. */
    public int top() {
        return queue.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

一個元素預設尾部插入,應該讓被插入的元素進入佇列的首部,