從今天開始阿偉要學習棧啦!!
(首先補充一個小知識點,引用作爲函數形參)
首先給出棧的抽象類:
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;
}