1.栈简介
虽然C++已经提供了栈,但是此处还是自己创建栈,目的是学习如何实现这些数据结构.
定义:是特殊的线性表,插入和删除都在同一端进行,这一端称为栈顶,另一端称为栈底.
2.栈的抽象数据类型
C++抽象类栈的代码如下:
//C++抽象类栈
template<class T>
class stack
{
virtual ~stack(){}
virtual bool empty() const=0;
virtual int size() const=0;
virtual T & top()=0;
virtual void pop()=0;
virutal void push(const T & theElement)=0;
};
3.数组描述
此处给出数组描述栈类的代码,栈底元素是stack[0],栈顶是stack[stackTop].
//类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();
}
void push(const T & theElement)
pravate:
int stackTop;//当前栈顶
int arrayLength;//栈容量
T * stack;//元素数组
};
template<class T>
arrayStack<T>::arrayStack(int initialCapacity)
{
if (initialCapacity<1)
{
ostringstream s;
s<<"Initial capacity="<<intitialCapacity<<"Must be >-";
throw illegalParameteValue(s.str());
}
arrayLength=initialCapacity;
stack=new T[arrayLength];
stackTop=-1;
}
template<class T>
void arrayStack<T>::push(const T & theElement)
{
if (stackTop==arrayLength-1)
{
changeLength1D(stack,arrayLength,2*arrayLength);
arrayLength*=2;
}
stack[++stackTop]=theElement;
}
4.链表描述
若用链表描述栈时,需确定用链表的那一端表示栈顶,若用链表的右端为栈顶,则每一个链表方法都为O(size()).
若用左端,都为O(1).选左端为其栈顶.
一个链栈的代码如下:
//定制链表栈
template<class T>
class linkedStack:public stack<T>
{
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);
stackSize++;
}
private:
chainNode<T>*stackTop;//栈顶指针
int stackSize;
};
template<class T>
linkedStack<T>::~linkedStack()
{
//析构函数
while (stackTop!=NULL)
{
//删除栈顶节点
chainNode<T>* nextNode=stackTop->next;
delete stackTop;
stackTop=nextNode;
}
}
template<class T>
void linkedStack<T>::pop()
{
if (stackSize==0)
throw stackEmpty();
chainNode<T>* nextNode=stackTop->next;
delete stackTop;
stackTop=nextNode;
stackSize--;
}
接下来有相关内容继续补充上来,欢迎大家批评指正.