栈的基本操作

栈的基本操作

注:利用模板类建类,进行栈定义
模板类定义在整个类定义之前

#include<iostream>
#include<string>
#include<cassert>
using namespace std;
template<class Type> class Stack {
private:
    Type *urls;
    int max_size, top_index;
public:
    Stack(int length_input) {
        urls = new Type[length_input];
        max_size = length_input;
        top_index = -1;
    }
    ~Stack() {
        delete[] urls;
    }
    bool push(const Type &element) {
        if (top_index >= max_size - 1) {
            return false;
        }
        top_index++;
        urls[top_index] = element;
        return true;
    }
    bool pop() {
        if (top_index < 0) {
            return false;
        }
        top_index--;
        return true;
    }
    Type top(){
        assert(top_index>=0);
        return urls[top_index];
    }
};
int main() {
    int n, m;
    cin >> n >> m;
    Stack<string> stack(n);
    for (int i = 1; i <= m; i++) {
        int opr;
        cin >> opr;
        if (opr == 0) {
            string element;
            cin >> element;
            if (stack.push(element)) {
                cout << "push success!" << endl;
            } else {
                cout << "push failed!" << endl;
            }
        } else if (opr == 1) {
            if (stack.pop()) {
                cout << "pop success!" << endl;
            } else {
                cout << "pop failed!" << endl;
            }
        }
        else if(opr==2){
            cout<<stack.top()<<endl;
        }
    }
    return 0;
}

你可能感兴趣的:(栈)