題目地址:https://leetcode-cn.com/problems/implement-stack-using-queues/
題目:
使用隊列實現棧的下列操作:
push(x) -- 元素 x 入棧
pop() -- 移除棧頂元素
top() -- 獲取棧頂元素
empty() -- 返回棧是否為空
試題分析:
這道題和232這道題一樣,只是數據結構反過來實現,利用隊列來實現棧,實現原理也是雷同,都是通過兩個隊列來實現堆棧的FILO的功能,在操作上也是一個進隊列一個出隊列,每次在push和pop的時候都要進行循環的在兩個隊列中導出導入,232和225在面試過程中是非常常見的一道算法題,能夠考驗你對隊列和棧的特性理解和靈活使用。
public class ImplementStackUsingQueues_225 {
private Queue queueIn;
private Queue queueOut;
/** Initialize your data structure here. */
public ImplementStackUsingQueues_225() {
queueIn = new LinkedBlockingQueue();
queueOut = new LinkedBlockingQueue();
}
/** Push element x onto stack. */
public void push(int x) {
while(!queueOut.isEmpty()){
queueIn.add(queueOut.poll());
}
queueIn.add(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
while(!queueOut.isEmpty()){
queueIn.a
轉自簡書作者monkey01
聯繫作者:xiaowanzi02620