数据结构实验三Word文件下载.docx
《数据结构实验三Word文件下载.docx》由会员分享,可在线阅读,更多相关《数据结构实验三Word文件下载.docx(10页珍藏版)》请在冰豆网上搜索。
进栈前,首先要判断栈是否为满,即top-base是否大于等于stackSize。
如果是,则要重新申请栈的顺序存储空间,然后把现有栈中的数据元素复制到新的存储空间,再进行上面的压入操作。
2.弹出栈顶的元素到e
出栈时,先将栈顶指针减1,再读取栈顶指针所指单元的数据元素。
出栈前,应该先判断栈是否为空。
如果栈为空,则没有元素可供弹出。
3.读栈顶的元素
读取栈顶指针所指单元的前面一个数据元素,不要移动栈顶指针。
读栈顶的元素之前,也应该先判断栈是否为空。
如果栈为空,则没有可供读取的元素。
4.判断栈是否为空
判断栈顶指针top是否等于栈底指针base。
如果相等,则为空栈。
五、实验数据及处理结果
源程序:
//头文件代码
#defineNULL0
#defineOK1
#defineERROR0
typedefboolStatus;
//顺序栈类c++语言定义
#include<
assert.h>
#ifndefMYHEAD_H
#defineMYHEAD_H
#include"
myhead.h"
#endif
#defineSTACK_MAX_SIZE50
#defineSTACKINCREMENT20
template<
typenameElemType>
classSqStack
{
public:
voidclear();
intgetLength();
intgetstackSize();
intgetTop(ElemTypee);
boolisEmpty();
SqStack<
ElemType>
operator=(SqStack<
rightS);
Statuspop(ElemType&
e);
voidpush(ElemTypee);
SqStack();
virtual~SqStack();
SqStack(constSqStack<
&
otherS);
/*intprint(inte)
{
intk;
int*ptr;
ptr=newint[e];
ptr=base;
//if(!
base)
//returnERROR;
//else
//{
for(inti=0;
i<
e;
i++)
{
k=*(ptr+i);
pop(k);
}
for(i=e;
i>
0;
i--)
cout<
<
*(ptr+i)<
'
'
;
cout<
endl;
delete[]ptr;
returnOK;
//}
}*/
protected:
ElemType*base;
ElemType*top;
intstackSize;
};
//置空
voidSqStack<
:
clear()
top=base;
}
//个数
intSqStack<
getLength()
returntop-base;
//空间大小
getstackSize()
returnstackSize;
//读栈顶元素
getTop(ElemTypee)
if(isEmpty())
returnERROR;
else
e=*(top-1);
returne;
//判断是否为空
boolSqStack<
isEmpty()
return(top==base?
true:
false);
//重载赋值运算符定义
SqStack<
SqStack<
operator=(SqStackrightS)
intlength=rights.getLength();
if(this!
=&
rightS)
{
if(stackSize<
rightS.stackSize)
delete[]base;
base=newElemType[right.stackSize];
assert(base!
=0);
stackSize=rightS.stackSize;
}
for(inti=0;
length;
*(base+i)=*(rightS.base+i);
top=base+length;
}
return*this;
//弹出栈顶的元素到e
StatusSqStack<
pop(ElemType&
e)
e=*--top;
returnOK;
//在栈顶压入元素e
push(ElemTypee)
intlength=top-base;
ElemType*newbase;
if(top-base>
=stackSize)
newbase=newElemType[stackSize+STACKINCREMENT];
assert(newbase!
for(intj=0;
j<
j++)
*(newbase+j)=*(base+j);
delete[]base;
stackSize+=STACKINCREMENT;
base=newbase;
*top=e;
++top;
//构造函数
SqStack()
base=newElemType[STACK_MAX_SIZE];
assert(base!
stackSize=STACK_MAX_SIZE;
//析构函数
~SqStack()
if(base)
delete[]base;
stackSize=0;
top=base=NULL;
//拷贝初始化构造函数
SqStack(constSqStack&
otherS)
intlength;
length=otherS.top-otherS.base;
base=newElemType[otherS.stackSize];
stackSize=otherS.stackSize;
for(inti=0;
*(base+i)=*(otherS.base+i);
top=base+length;
//顺序栈的测试函数
iostream>
#ifndefSQSTACK_CPP
#defineSQSTACK_CPP
#include"
sqstack.cpp"
usingnamespacestd;
intmain()
int>
obj1;
intn,a,b=0,s=0;
cout<
"
已分配空间stacksize="
obj1.getstackSize()<
请输入您要进栈的数的个数:
cin>
>
n;
请输入您要进栈的数(输入10000停止进栈):
for(inti=1;
=n;
cin>
a;
if(a==10000)
break;
else
obj1.push(a);
++s;
当前元素个数为:
obj1.getLength()<
读取当前栈顶元素为"
obj1.getTop(b)<
obj1.pop(a);
--s;
弹出栈顶元素"
a<
到a后的栈为:
intelem[20];
for(i=0;
s;
obj1.pop(elem[i]);
for(i=s;
cout<
elem[i-1]<
return0;
实验结果:
六、实验过程分析与小结