面試題9——兩個棧實現一個隊列

自己的思路:
主要思路是一個棧當主要的執行操作,另一個作爲輔助棧。有兩種思路:主要棧的棧頂即爲隊列的頭,棧底爲隊列的尾。另一種反過來,棧頂爲尾,棧底爲頭。
直接寫代碼:
把棧頂當作隊列的尾

#include<stack>
#include<iostream>

using namespace std;

stack<int> s1;
stack<int> s2;
class Q{
public:
    void appendTail(int a){
        s1.push(a);
    };
    
    void deleteHead(){
        int temp;
        if(s1.empty()){
            cout<<"error"<<endl;
            return;
        }
        else{
            while(!s1.empty()){
                temp = s1.top();
                s1.pop();
                s2.push(temp);
            }
            s2.pop();
            while(!s2.empty()){
                temp = s2.top();
                s2.pop();
                s1.push(temp);
            }
        }
    };
    void que_pop(){
        int temp;
        if(s1.empty()){
            cout<<"empty"<<endl;
        }
        else{
            while(!s1.empty()){
                temp = s1.top();
                s1.pop();
                s2.push(temp);
            }
            cout<<s2.top()<<endl;
            while(!s2.empty()){
                temp = s2.top();
                s2.pop();
                s1.push(temp);
            }
        }
    };
};
int main(){
    Q que;
    int temp;
    cout<<"input:";
    std::cin >> temp;
    que.appendTail(temp);
    que.que_pop();
    return 0;
    
}

代碼調BUG:
1、c++類中的成員函數必須聲明是public,protected,private。
2、pop函數按理來說應該會返回棧頂的值然後再刪除,但是貌似這裏並沒有返回值,直接刪除了。
3、主函數main必須定義成int類型。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章