天天看點

JZ5. 用兩個棧實作隊列

題目描述:用兩個棧來實作一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。

1. 分析

​ 用兩個棧實作隊列,即要實作先入先出的規則。于是乎,stack1專門用來儲存資料,stack2用來輔助:

  1. push:用stack1來儲存每次push進來的資料;
  2. pop:将stack1中除了最後一個元素之外的其他所有元素全部倒入到stack2中,然後将stack1中最後一個元素作為傳回值pop出來;然後再把stack2中所有元素再push到stack1中即可。這樣就實作了先入先出的原則。

2. 用C++寫出邏輯:

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        while(stack1.size() != 1){
            stack2.push(stack1.top());
            stack1.pop();
        }
        int val = stack1.top();
        stack1.pop();
        while(!stack2.empty()){
            stack1.push(stack2.top());
            stack2.pop();
        }
        return val;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
           

繼續閱讀