Leetcode - Implement Stack using Queues

My code:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

class MyStack {
    private Queue<Integer> q = new LinkedList<Integer>();
    // Push element x onto stack.
    public void push(int x) {
        q.offer(x);
    }

    // Removes the element on top of the stack.
    public void pop() {
        if (q.isEmpty())
            return;
        ArrayList<Integer> temp = new ArrayList<Integer>(q.size());
        int len = q.size();
        for (int i = 0; i < len; i++) {
            temp.add(q.poll());
        }
        for (int i = 0; i < len - 1; i++)
            q.offer(temp.get(i));
    }

    // Get the top element.
    public int top() {
        if (q.isEmpty())
            return - 1;
        ArrayList<Integer> temp = new ArrayList<Integer>(q.size());
        int len = q.size();
        for (int i = 0; i < len; i++) {
            temp.add(q.poll());
        }
        int ret = temp.get(temp.size() - 1);
        for (int i = 0; i < len; i++)
            q.offer(temp.get(i));
        return ret;
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return q.isEmpty();
    }
    
    public static void main(String[] args) {
        MyStack test = new MyStack();
        test.push(1);
        System.out.println(test.top());
    }
}

昨天跟人吹牛,導致今天早上連簡單題都做不出來了。
不是做不出來,而是腦子用不動了。感覺昨天用腦過度了。然后又沒睡好。
這道題目有個注意點是我沒考慮到的,雖然是簡單題。
ArrayList<Integer> t = new ArrayList<Integer>(10);
那么, t.size() 等于多少?
我誤認為了10
其實不是,還是0.
ArrayList 之前總結過。
這個10,表示申請了一個Object[]數組,長度為10.
但是,不代表 arraylist size = 10.
size 仍然是0.
他和object數組長度是無關的,他等于,object 數組中有效元素的個數。
剛開始初始化的時候,數組里面都是null,所以size = 0

**
總結: ArrayList size 的具體意義
**

Anyway, Good luck, Richardo!

My code:

class MyStack {
    private Queue<Integer> q = new LinkedList<Integer>();
    // Push element x onto stack.
    public void push(int x) {
        q.offer(x);
        int size = q.size();
        while (size > 1) {
            q.offer(q.remove());
            size--;
        }
    }

    // Removes the element on top of the stack.
    public void pop() {
        q.poll();
    }

    // Get the top element.
    public int top() {
        return q.peek();
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return q.isEmpty();
    }
}

我以為有更好的方法,沒想到還是如此:
push O(n)
pop O(1)
然后可以用Queue來完成。

reference:
https://leetcode.com/articles/implement-stack-using-queues/#approach-1-two-queues-push-o1-pop-on

還有種O(1)的方法,太偏門了。
https://discuss.leetcode.com/topic/15961/o-1-purely-with-queues

Anyway, Good luck, Richardo! -- 09/11/2016

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容