数据结构学习——栈的数组描述

从今天开始阿伟要学习栈啦!!
(首先补充一个小知识点,引用作为函数形参

首先给出栈的抽象类:

template<class T>
class stack
{
public:
    virtual ~stack(){}//析构函数
    virtual bool empty()const=0;//返回true,当且仅当栈为空
    virtual int size()const=0;//返回栈中元素个数
    virtual T& top()=0;//返回栈顶元素的引用
    virtual void pop()=0;//删除栈顶元素
    virtual void push(const T& theElement)=0;//将元素theElement压入栈顶
};

栈的数组描述是从类arrayList和stack派生的类derivedArrayStack(derived:派生的)

//操作在数组尾进行,即栈顶在数组尾
template<class T>
class derivedArrayStack:private arrayList<T>,public:stack<T>
{
public:
    //动态创建一维数组,数组长度是initialCapacity
    derivedArrayStack(int initialCapacity=10):arrayLength<T>(initialCapacity){}//构造函数
    bool empty()const
    {
        return arrayList<T>::empty();
    }
    int size()const
    {
        return arrayList<T>::size();
    }
    T& top()
    {
        if(arrayList<T>::empty())
            throw stackEmpty();
        return get(arrayList<T>::size()-1);
    }
    void pop()
    {
        if(arrayList<T>::empty())
            throw stackEmpty();
        erase(arrayList<T>::size()-1);
    }
    void push(const T& theElement)
    {
        insert(arrayList<T>::size(),theElement);
    }
};

为了得到一个性能更好的数组栈的实现方法,一个途径就是开发一个类,利用数组stack来包含所有的栈元素。
arrayStack类:

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;
    }
    T& top()
    {
        if(stackTop==-1)
            throw stackEmpty();
        return stack[stackTop];
    }
    void pop()
    {
        if(stackTop==-1)
            throw stackEmpty;
        stack[stackTop--].~T();//T的析构函数
    }
    void push(const T& theElement);
private:
    int stackTop;//当前栈顶元素的索引
    int arrayLength;//栈容量
    T *stack;//元素数组
};

构造函数(时间复杂度O(1))

template<class T>
arrayStack<T>::arrayStack(int initialCapacity)
{
    if(initialCapacity<1)
    {
        ostringstream s;
        s<<"Initial capacity ="<<initialCapacity<<"Must be > 0";
        throw illegalParameterValue(s.str());
    }
    arrayLength=initialCapacity;
    stack=new T[arrayLength];
    stackTop=-1;
}

push函数的实现

template<class T>
void arrayStack<T>::push(const T& theElement)
{
    if(stackTop==arrayLength-1)//如果空间已满,容量加倍
    {
        changeLength1D(stack,arrayLength,2*arrayLength);
        arrayLength*=2;
    }
    //在栈顶插入
    stack[++stackTop]=theElement;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值