1. 程式人生 > 實用技巧 >LeetCode 225. 用佇列實現棧

LeetCode 225. 用佇列實現棧

class MyStack {
    //定義一個佇列
    Queue<Integer> queue = new LinkedList<>();
    /** Initialize your data structure here. */
    public MyStack() {

    }
    
    /** Push element x onto stack. */
    //佇列是先進先出,棧為先進後出,用佇列模擬棧時,新增一個元素是在佇列的末尾,彈出一個元素是在隊頭
    //此時把該元素前面的元素全部出隊,該元素就到了隊首,其餘元素再進隊,即為一個棧先進後出的順序
public void push(int x) { queue.add(x); int count = queue.size(); while(count > 1){ queue.add(queue.remove()); count--; } } /** 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();
*/