Finished school array describing the stack, the stack to learn Wei chain describes QAQ
According to the analysis, with the left end of the stack as a linked list of more efficient
Develop a class 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++;
}
};
Destructor
template<class T>
linkedStack<T>::~linkedStack()
{
while(stackTop!=NULL)
{
chainNode<T>* nextNode=stackTop->next;
delete stackTop;
stackTop=nextNode;
}
}
Achieve pop function
//删除栈顶节点
template<class T>
void linkedStack<T>::pop()
{
if(stackSize==0)
throw stackEmpty();
chainNode<T>* nextNode=stackTop->next;
delete stackTop;
stackTop=nextNode;
stackSize--;
}