栈(数组实现)

版权声明: https://blog.csdn.net/moon_sky1999/article/details/83998899

外接线性表(数组实现)。

#pragma once

#include "arrayList.h"

template<class T>
class stack {
public:
    virtual ~stack() {}

    virtual bool empty() const = 0;

    virtual int size() const = 0;

    virtual T &top() = 0;

    virtual void pop() = 0;

    virtual void push(const T &theElement) = 0;
};

template<class T>
class arrayStack : public stack<T> {
public:
    arrayStack(int initalCapacity = 10);

    ~arrayStack() { delete[]stack; }

    bool empty() const { return stackTop == -1; }

    int size() const { return stackTop + 1; }

    T &top();

    void pop();

    void push(const T &theElement);

private:
    int stackTop;
    int arrayLength;
    T *stack;
};

template<class T>
arrayStack<T>::arrayStack(int initalCapacity) {
    if (initalCapacity < 1)
        throw "error";
    arrayLength = initalCapacity;
    stack = new T[arrayLength];
    stackTop = -1;
}

template<class T>
T &arrayStack<T>::top() {
    if (stackTop == -1)throw "empty";
    return stack[stackTop];
}

template<class T>
void arrayStack<T>::pop() {
    if (stackTop == -1)throw "empty";
    stack[stackTop--].~T();
}

template<class T>
void arrayStack<T>::push(const T &theElement) {
    if (stackTop == arrayLength - 1) {
        changeLength1D(stack, arrayLength, 2 * arrayLength);
        arrayLength *= 2;
    }
    stack[++stackTop] = theElement;
}

猜你喜欢

转载自blog.csdn.net/moon_sky1999/article/details/83998899