1. 程式人生 > 其它 >構建陣列棧類

構建陣列棧類

構建陣列棧類

程式碼

#include <iostream>

using namespace std;

// 改變一個一維陣列的長度
template<class T>
void changeLength1D(T *&a, int oldLength, int newLength) {
    if (newLength < 0)
        cerr << "new Length must be > 0";
    T *temp = new T[newLength];
    int number = min(oldLength, newLength);
    copy(a, a + number, temp);
    delete[]a;
    a = temp;
}

template<class T>
class arrayStack {
public:
    explicit arrayStack(int initialCapacity = 10);

    ~arrayStack() { delete[] stack; }

    int illegalParameterValue(const string &s) {
        cout << s << endl;
        return -1;
    }

    [[maybe_unused]] [[nodiscard]] bool empty() const { return stackTop == -1; }

    [[maybe_unused]] [[nodiscard]] int size() const { return stackTop + 1; }

    [[maybe_unused]] T &top() {
        if (stackTop == -1)
            throw illegalParameterValue("Stack Empty");
        return stack[stackTop];
    }

    void pop() {
        if (stackTop == -1)
            throw illegalParameterValue("Stack Empty");
        stack[stackTop--].~T();
    }

    void push(const T &theElement);

    [[nodiscard]] int getStackTop() const;

    [[maybe_unused]] [[nodiscard]] int getArrayLength() const;

    T *getStack() const;;

private:
    int stackTop; // 當前棧頂
    int arrayLength; // 棧容量


    T *stack; // 元素陣列
};

template<class T>
arrayStack<T>::arrayStack(int initialCapacity) {
    // 建構函式
    if (initialCapacity < 1)
        throw illegalParameterValue("initialCapacity must be > 0");
    arrayLength = initialCapacity;
    stack = new T[arrayLength];
    stackTop = -1;
}

template<class T>
void arrayStack<T>::push(const T &theElement) {
    // 將元素壓入棧
    if (stackTop == arrayLength - 1) {
        // 空間已滿,容量加倍
        changeLength1D(stack, arrayLength, arrayLength * 2);
        arrayLength *= 2;
    }
    // 在棧頂插入
    stack[++stackTop] = theElement;
}

template<class T>
int arrayStack<T>::getStackTop() const {
    return stackTop;
}

template<class T>
[[maybe_unused]] int arrayStack<T>::getArrayLength() const {
    return arrayLength;
}

template<class T>
T *arrayStack<T>::getStack() const {
    return stack;
}

template<class T>
ostream &operator<<(ostream &out, arrayStack<T> &stack) {
    int stackTop = stack.getStackTop();
    T *element = stack.getStack();
    for (int i = stackTop; i >= 0; --i)
        out << element[i] << ' ';
    return out;

}

int main() {
    auto *stack1 = new arrayStack<int>(20);
    for (int i = 0; i < 20; ++i)
        stack1->push(i);
    cout << *stack1<<"所儲存資料Size:"<<stack1->size() << endl;
    stack1->pop();
    cout << *stack1<<"所儲存資料Size:"<<stack1->size() << endl;
    cout<<"棧頂元素"<<endl;
    cout << stack1->top() << endl;
    return 0;
}

執行結果

19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 所儲存資料Size:20
18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 所儲存資料Size:19
棧頂元素
18