【左神算法】隊列實現棧

隊列實現棧

/** Initialize your data structure here. */
    private Queue<Integer> q;
    private Integer tail;//記錄棧頂元素

    public MyStack() {
        q = new LinkedList<>();
        tail = 0;
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        q.add(x);
        tail = x;//每添加一個元素 就將最後一個元素賦值給tail
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        for(int i=0;i<q.size()-2;i++){
            q.add(q.remove());
        }
        tail = q.remove();//將倒數第二個元素存儲到tail 用以彈出tail
        q.add(tail);
        return q.remove();
    }
    
    /** Get the top element. */
    public int top() {
        return tail;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q.isEmpty();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章