面试题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类型。

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