从今天开始阿伟要学习栈啦!!
(首先补充一个小知识点,引用作为函数形参)
首先给出栈的抽象类:
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;
}