1.栈的ADT
template <typename E> class Stack {
private:
void operator=(const Stack&){}
stack(const Stack&){}
public:
Stack(){}
virtual ~Stack(){}
virtual void clear()=0;
virtual void push(const E& it)=0;
virtual E pop()=0;
virtual const E& topValue() const=0;
virtual int length() const=0;
};
2.顺序栈类的实现
top定义为表示栈中的第一个空闲位置。空栈的top=0,即第一个空闲位置。
template <typename E> class AStack:public Stack<E>{
private:
int maxSize;
int top;
E *listArray;
public:
AStack(int size=defaultSize)
{ maxSize=size; top=0; listArray=new E[size]; }
~AStack() { delete [] listArray; }
void clear() { top=0; }
void push(const E& it){
Assert(top!=maxSize,"Stack is full");
listArray[top++]=it;
}
E pop() {
Assert(top!=0,"Stack is empty");
return listArray[--top];
}
const E& topValue() const {
Assert(top!=0,"Stack is empty");
return listArray[top-1];
}
int length() const { return top; }
};
3.链式栈
链式栈唯一的数据成员是top,它是一个指向链式栈第一个结点(栈顶)的指针。
template <typename E> class Link {
public:
E element;
Link *next;
Link(const E& elemval,Link * nextval=NULL)
{ element=elemval; next=nextval;}
Link(Link* nextval=NULL) { next=nextval;}
};
template <typename E> class LStack:public Stack<E>{
private:
Link<E>* top;
int size;
public:
LStack(int sz=defaultSize)
{ top=NULL; size=0; }
~LStack() { clear(); }
void clear() {
while(top!=NULL){
link<E>* temp=top;
top=top->next;
delete temp;
}
size=0;
}
void push(const E& it){
top=new Link<E>(it,top);
size++;
}
E pop(){
Assert(top!=NULL,"Stack is empty");
E it=top->element;
Link<E>* ltemp=top->next;
delete top;
top=ltemp;
size--;
return it;
}
const E& topValue() const{
Assert(top!=0,"Stack is empty");
return top->element;
}
int length() const { return size; }
};
如何通过链式栈找到链中n/2处的数值:
可以用两个指针,快指针两个两个结点的走,慢指针一个一个结点的走。当快指针到达栈底时,慢指针恰好到中间。