Data structure learning - an array describing the stack

Starting today Awei stack to learn it! !
(First supplement a little knowledge, cited as a function parameter )

Firstly stack abstract class:

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压入栈顶
};

Description stack array is derived from the class arrayList and stack class derivedArrayStack (derived: 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);
    }
};

In order to obtain a method to achieve a better performance of the stack array, a way is the development of a class , by using the array containing all of the stack to stack the elements.
arrayStack categories:

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;//元素数组
};

Constructor (time complexity of 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;
}

Realization push function

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

Published 32 original articles · won praise 12 · views 1370

Guess you like

Origin blog.csdn.net/qq_18873031/article/details/103206270