栈的操作算法c语言实现

很急,求大神帮忙,谢谢,思密达
2025-03-10 06:12:38
推荐回答(1个)
回答1:

#include
using namespace std;
#define STACK_INIT_SIZE 100
#define STACKINCREASE 1ypedef struct{
int *base;
int *top;
int stacksize;
}SqStack;
int InitStack (SqStack &S)//构造空栈
{
S.base=(int *)malloc(STACK_INIT_SIZE*sizeof(int));
if(!S.base)exit(OVERFLOW);//存储分配失败
S.top=S.base;
return 0;
}
int Push(SqStack &S,int e)//插入新的元素为新的栈顶元素
{
if(S.top-S.base>=S.stacksize)//z栈满,追加存储空间
{
S.base=(int *)realloc(S.base,(S.stacksize+STACKINCREASE)*sizeof(int));
if(!S.base)exit(OVERFLOW);//存储失败
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREASE;
}
*S.top++ =e;//认为是先赋值再加加?
return 0;
}
void Insert(SqStack &S,int e)
{
int *p;
int temp;
p=S.base;
if(S.top-S.base>=S.stacksize)//z栈满,追加存储空间
{
S.base=(int *)realloc(S.base,(S.stacksize+STACKINCREASE)*sizeof(int));
if(!S.base)exit(OVERFLOW);//存储失败
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREASE;
}
while(*p<=e)
p++;
while(p {
temp=*p;
*p=e;
e=temp;
p++;
}
}0
void Pop(SqStack S)
{
if(S.base==S.top)
cout<<"该栈是空栈"< while(S.base {
cout<<*++S.base<<" ";
}
}
void main()
{
SqStack S;
int j,i;
InitStack(S);
for(i=1;i<=5;i++)
{
cout<<"请输入"< cin>>j;
Push(S,j);
}
Pop(S);
cout<<"请输入你要插入的元素"< cin>>j;
Insert(S,j);
cout<<"输出栈内元素"< Pop(S);

}