學完了棧的數組描述,阿偉要學習棧的鏈式描述了QAQ
根據分析,用鏈表的左端作爲棧頂更加高效
開發一個類linkedStack
template<class T>
class linkedStack:public stack<T>
{
private:
chainNode<T>* stackTop;//棧頂指針
int stackSize;//棧中元素個數
public:
linkedStack(int initialCapacity=10)
{
stackTop=NULL;
stackSize=0;
}
~linkedStack();//析構函數
bool empty()const
{
return stackSize==0;
}
int size()const
{
return stackSize;
}
T& top()
{
if(stackSize==0)
throw stackEmpty();
return stackTop->element;
}
void pop();
void push(const T& theElement)
{
stackTop=new chainNode<T>(theElement,stackTop);
//調用chainNode的構造函數,stackTop爲next值
stackSize++;
}
};
析構函數
template<class T>
linkedStack<T>::~linkedStack()
{
while(stackTop!=NULL)
{
chainNode<T>* nextNode=stackTop->next;
delete stackTop;
stackTop=nextNode;
}
}
pop函數的實現
//刪除棧頂節點
template<class T>
void linkedStack<T>::pop()
{
if(stackSize==0)
throw stackEmpty();
chainNode<T>* nextNode=stackTop->next;
delete stackTop;
stackTop=nextNode;
stackSize--;
}