#include<iostream>
using namespace std;
typedef int ElemType ;
#define init_space 100
#define incre_space 10
struct SequenceStack{
ElemType *base;
ElemType *top;
int stacksize;
};
int init(SequenceStack &SS)
{
SS.base=(ElemType*)malloc(sizeof(ElemType)*init_space);
if(!SS.base)
{
cout<<"初始化分配失败"<<endl;
exit(-1);
}
SS.top=SS.base;
SS.stacksize=init_space;
return 1;
}
int push(SequenceStack &ss,ElemType e)
{
if((ss.top-ss.base)>=ss.stacksize)
{
ss.base=(ElemType*)realloc(ss.base,sizeof(ElemType)*(init_space+incre_space));
if(!ss.base)
{
cout<<"内存重新分配失败"<<endl;
exit(-1);
}
ss.top=ss.base+ss.stacksize;
ss.stacksize+=incre_space;
}
*ss.top++=e;
return 1;
}
int pop(SequenceStack &ss,ElemType &e)
{
if(ss.base==ss.top)
{
cout<<"栈为空,不能进行出栈操作"<<endl;
exit(0);
}
e=*(--ss.top);
return 1;
}
int get_top(SequenceStack &ss,ElemType &e)
{
if(ss.base==ss.top)
{
cout<<"栈为空"<<endl;
exit(-1);
}
e=*(ss.top-1);
return 1;
}
//遍历栈
void printStack(SequenceStack &ss)
{
ElemType *temp;
temp=ss.base;
if(ss.top==ss.base)
{
cout<<"为空"<<endl;
exit(-1);
}
while(temp!=ss.top)
{
cout<<*temp<<endl;
temp++;
}
}
void main()
{
SequenceStack ss;
init(ss);
push(ss,1);
push(ss,2);
push(ss,3);
printStack(ss);
int e,e2;
get_top(ss,e);
cout<<e<<endl;
pop(ss,e2);
cout<<e2<<endl;
cout<<ss.base[0]<<endl;
system("pause");
}
栈的线性存储
最新推荐文章于 2021-04-26 16:33:05 发布