Leetcode 225. Implement Stack using Queues

最近一直在忙一些個人的私事,導(dǎo)致好多計劃都中斷了。說多了都是借口,歸根結(jié)底是自己沒有規(guī)劃好時間,堅持做下去,下面回正題繼續(xù)做題。

Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.

思路:
一、自己的第一個思路是用兩個queue和一個變量top,一個queue專門負(fù)責(zé)存push進(jìn)來的元素,一個queue負(fù)責(zé)在pop的時候臨時存放push queue中前n-1個元素,top用來存當(dāng)前最后一個push進(jìn)來的元素。
在pop的時候,需要先把push queue前n-1個元素移動到pop queue,把push queue最后一個元素remove以后,再把push queue和pop queue交換。

二、在solution里看到第三種方法十分巧妙,用一個queue就可以實現(xiàn)。每次push把元素添加到隊列以后,就把隊列前n-1個元素重新入隊。下面以依次push 1到4為例:
1-->1,2-->2,1-->2,1,3-->3,2,1-->3,2,1,4-->4,3,2,1
可以看到每次push元素后,隊列就變成了相應(yīng)的stack表達(dá)。
下面發(fā)一下第二種方法的代碼:

public class HA_StackByQueue {
private Queue<Integer> queue;

/** Initialize your data structure here. */
public HA_StackByQueue() {
    this.queue = new LinkedList<>();
}

/** Push element x onto stack. */
public void push(int x) {
    this.queue.offer(x);
    int size = this.queue.size();
    while (size > 1) {
        this.queue.offer(this.queue.poll());
        size--;
    }
}

/** Removes the element on top of the stack and returns that element. */
public int pop() {
    return this.queue.poll();
}

/** Get the top element. */
public int top() {
    return this.queue.peek();
}

/** Returns whether the stack is empty. */
public boolean empty() {
    return this.queue.isEmpty();
}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容