用数组实现栈(C++)

2020-12-13 14:22

阅读:355

标签:public   article   system   默认构造函数   异常捕获   csdn   构造   pac   动态   

#include 
//栈的数组实现
using namespace std;
#define MAXSIZE 10;

template
class Stack
{
public:
    //默认构造函数
    Stack();
    Stack(size_t maxElements);
    Stack(T data[], size_t maxElements);
    ~Stack();

    //入栈
    void Push(T data);

    //出站并返回
    T Pop();

    //返回栈顶元素
    T Top();

    //判断是否为空栈
    bool isEmpty();

    //栈是否已满
    bool isFull();

    //清空栈
    void Clear();

    //获得栈元素个数
    size_t GetSize();
private:
    //栈标指示器
    size_t top;

    //数组
    T *arrays;

    //栈的容量
    size_t maxSize;
};

template
Stack::Stack() : maxSize(MAXSIZE), top(-1)
{
    arrays = new T[maxSize];
    if (arrays == NULL)
    {
        cout 
Stack::Stack(size_t maxElements) : maxSize(maxElements), top(-1)
{
    arrays = new T[maxSize];
    if (arrays == NULL)
    {
        cout 
Stack::Stack(T data[], size_t maxElements) : maxSize(maxElements), top(-1)
{
    arrays = new T[maxSize];//创建存储栈的数组
    for (size_t i = 0; i 
Stack::~Stack()
{
    delete[] arrays;
}

template
void Stack::Push(T data)
{
    if (isFull())
    {
        throw runtime_error("Full stack");
    }
    else
    {
        top++;//指向栈顶
        arrays[top] = data;
    }
}

template
T Stack::Pop()
{
    if (isEmpty())
    {
        throw runtime_error("No elements in the stack");
    }
    else
    {
        T data = arrays[top];
        top--;
        return data;
    }
}

template
T Stack::Top()
{
    if (isEmpty())
    {
        throw runtime_error("No elements in the stack");
    }
    else
    {
        return arrays[top];
    }
}

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

template
bool Stack::isFull()
{
    return top == maxSize - 1;
}

template
void Stack::Clear()
{
    while (Top != -1)
    {
        Top--;
    }
}

template
size_t Stack::GetSize()
{
    return top + 1;
}

int main()
{
    try//异常捕获
    {
        int a[6] = { 1, 2, 3, 4, 5, 6 };
        Stack s(a, 6);
        s.Pop();
        s.Push(7);
        for (int i = 0; i 

来源:c++ 栈的数组实现

用数组实现栈(C++)

标签:public   article   system   默认构造函数   异常捕获   csdn   构造   pac   动态   

原文地址:https://www.cnblogs.com/clwsec/p/11560147.html


评论


亲,登录后才可以留言!