数据结构之栈篇

栈是一种特殊的线性表 其插入(也称为入栈和压栈)和删除(出栈和弹栈)操作都在痛一端进行,一端为栈顶 一端为栈底


#include"stack.h"
#include"exception.h"
#include<algorithm>
#include<sstream>
using namespace std;

template<class T>

class arrayStack :public stack < T >
{
public:
    arrayStack(int initialCapacity = 10);//构造函数
    ~arrayStack(){ delete[] stack; }//析构函数

    bool empty() const{ return stackTop == -1; }
    int size() const { return stackTop + 1; }
    void changeLengthld(T* &a, int oldLength, int newLength);//栈容量已满的情况下增加栈容量的容量
    T & top() //返回栈顶元素
    {
        if (stackTop == -1)
        {
            throw stackEmpty();
        }
        else
        {
            return stack[stackTop];
        }
    }
    void pop() //删除栈顶元素
    {
        if (stackTop == -1)
        {
            throw stackEmpty();
        }
        stack[stackTop--].~T(); //T的析构函数 等价于stackTop--;
    }
    void push(const T& theElement);

private:
    int arrayLength; //栈容量
    int stackTop;//栈顶
    T *stack;//元素数组
};

template<class T>

arrayStack<T>::arrayStack(int initialCapacity)
{
    //构造函数
    if (initialCapacity < 1)
    {
        ostringstream s;
        s << "InitialCapacity = " << initialCapacity << "must be > 0";
        throw illegalParameterValue(s.str());
    }
    arrayLength = initialCapacity;
    stackTop = -1;
    stack = new T[arrayLength];
}
template<class T>

void arrayStack<T>::changeLengthld(T* &a, int oldLength, int newLength)
{
    if (newLength < 0)
        throw illegalParameterValue("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>
void arrayStack<T>::push(const T &theElement)
{
    if (stackTop == arrayLength - 1)
    {//栈容量已满 ,增加容量
        changeLengthld(stack, arrayLength, 2*arrayLength);
        arrayLength *= 2;
    }

    //栈顶插入
    stack[++stackTop] = theElement;
}
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;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值