数据结构之栈篇

来源:互联网 发布:淘宝优惠券名称怎么写 编辑:程序博客网 时间:2024/05/20 06:41

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

#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
原创粉丝点击