数据结构-栈-代码实现

#include 
#include 
using namespace std;
template<class T>
#define MAXSIZE 100

class Stack{
    private:
        T arr[MAXSIZE];
        int top;

    public:
        Stack() : top(-1) {}
        T pop() {
            if(top >= 0) {
                return arr[top--];
            }else {
                throw underflow_error("Stack Underflow");
            }
        }

        void push(T elem) {
            if(top < MAXSIZE - 1) {
                arr[++top] = elem;
            }else {
                throw overflow_error("Stack Overflow");
            }
        } 

        T peek() {
            if(top >= 0) {
                return arr[top];
            }else {
                throw overflow_error("Stack Overflow");
            }
        }

        bool isEmpty() {
            return top == -1;
        }

        int size() {
            return top + 1;
        }
};


int main() {
    Stack<int>* s = new Stack<int>();
    s->push(10);
    cout << "peek: ";
    cout << s->peek() << endl;
    cout << "pop: ";
    cout << s->pop() << endl;
    s->push(5);
    s->push(4);
    cout << "size: ";
    cout << s->size() << endl;
    return 0;
}

你可能感兴趣的:(数据结构,c++,算法)