b top→a top L top→空栈 M进栈 b进栈 top e top e d d C c b b L L e进栈 ∫进栈溢出 进栈示例 6
top 空栈 top top top top a 进栈 b 进栈 a a b a b c d e e 进栈 a b c d e f 进栈溢出 进栈示例 6
e top d d C top C C b b top b L L L e退栈 d退栈 C退栈 b top L L b退栈 top→a退栈 top→空栈 退栈示例
top c 退栈 b 退栈 a b a a 退栈 空栈 top a b d d 退栈 c top a b c top top top a b d e e 退栈 c 退栈示例7
顺序栈的操作 template <class E> void SeqStack<E>::overflowProcess( /私有数:当栈满则执行扩充栈存储空间处 理 E *newArray new E[2*maxSizel; 川创建更大的存储数组 for (inti=0;i<-top;i++) newArray[i]elements[i; maxSize +maxSize; delete elements; elements newArray; /改变elements指针 }; 8
8 顺序栈的操作 template <class E> void SeqStack<E>::overflowProcess() { //私有函数:当栈满则执行扩充栈存储空间处 理 E *newArray = new E[2*maxSize]; //创建更大的存储数组 for (int i = 0; i <= top; i++) newArray[i] = elements[i]; maxSize += maxSize; delete [ ]elements; elements = newArray; //改变elements指针 };
template <class E> void SeqStack<E>:Push(E x) /若栈不满,则将元素X插入该栈栈顶,否则溢出处理 if (IsFullO==true)overflowProcess(); /栈满 elements[++top]=x; /栈顶指针先加1,再进栈 }; template <class E> bool SeqStack<E>:Pop(E&x) /川丞数退出栈顶元素并返回栈顶元素的值 if (IsEmpty()==true)return false; x elements[top--]; 川栈顶指针退1 return true; 川退栈成功 }; 9
9 template <class E> void SeqStack<E>::Push(E x) { //若栈不满, 则将元素x插入该栈栈顶, 否则溢出处理 if (IsFull() == true) overflowProcess(); //栈满 elements[++top] = x; //栈顶指针先加1, 再进栈 }; template <class E> bool SeqStack<E>::Pop(E& x) { //函数退出栈顶元素并返回栈顶元素的值 if (IsEmpty() == true) return false; x = elements[top--]; //栈顶指针退1 return true; //退栈成功 };
template <class E> bool Seqstack<E>::getTop(E&x) /若栈不空则極数返回该栈栈顶元素的地址 if (IsEmpty()==true)return false; x elements[top]; return true; }; 10
10 template <class E> bool Seqstack<E>::getTop(E& x) { //若栈不空则函数返回该栈栈顶元素的地址 if (IsEmpty() == true) return false; x = elements[top]; return true; };