13. 定义一个顺序栈,依次将1,2,3,4四个元素入栈,取栈顶元素。

这个的源程序怎么样的啊,真的崩溃了- -
2025-04-29 03:29:27
推荐回答(1个)
回答1:

下面随便入几个元素都可以,栈的遍历就是从栈顶开始的取元素的,你要是只要一个栈顶元素,把循环去掉就好了#include
#include
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10template
class SqStack
{
ElemType *base;
int stacksize;
public:
ElemType *top;
SqStack() //初始化栈
{
base=new ElemType[STACK_INIT_SIZE];
top=base;
stacksize=STACK_INIT_SIZE;
}
void CreatStack(int n) //创建栈
{ if(n>STACK_INIT_SIZE)
{
ElemType *newbase;
newbase=new ElemType [stacksize+STACKINCREMENT];
base=newbase;
top=base;
stacksize+=STACKINCREMENT;
}
for(int i=0; i {
ElemType e;
cin>>e;
*top=e;
top++;
}
}
int StackLength()const //求栈长度
{
return top-base;
}

void Push(ElemType e) //入栈
{
if(StackLength()==stacksize)
{
ElemType *newbase;
newbase=new ElemType [stacksize+STACKINCREMENT];
base=newbase;
stacksize+=STACKINCREMENT;
}
*top=e;
top++;
}
void Pop(ElemType &e) //出栈
{
e=*(top-1);
*(top-1)=NULL;
top--;
}

void StackTraverse()const //遍历
{
ElemType *p=base;
while(p!=top)
{
cout<<*p<<'\t';
p++;
}
cout< }
}; void main()
{
SqStack S;
int x;
cin>>x;
S.CreatStack(x);
S.StackTraverse();
int y;
cin>>y;
S.Push(y);
S.StackTraverse();
int e;
S.Pop(e);
cout< S.StackTraverse();
}