栈是一种特殊的线性表 其插入(也称为入栈和压栈)和删除(出栈和弹栈)操作都在痛一端进行,一端为栈顶 一端为栈底
#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;
};