分类: C/C++
2008-09-19 20:50:46
void Push(SqStack &s, int e)
{
if(s.top -s.base >=s.stacksize) {//本满,追加存储空间
s.base=(int *)realloc(s.base,
(s.stacksize+StackIncreament)*sizeof(int));
if(!s.base) printf("error\n");
s.top=s.base+s.stacksize;
s.stacksize+=StackIncreament;
}
*s.top++=e;
}//向栈顶插入元素e
void InitStack(SqStack &s)
{
s.base=(int *)malloc(Stack_Init_Size*sizeof(int)); //栈底地址
if(!s.base) printf("error\n");
s.top=s.base;
s.stacksize =Stack_Init_Size;//构造空栈
printf("输入6个栈元素:");
for(int i=0;i<6;i++)
{
int a;
scanf("%d",&a);
Push(s,a);//向栈中插元素
}
}//初始化栈
int StackEmpty(SqStack s)
{
if(s.top ==s.base ) return 1;
else return 0;
}//判断栈是否为空
void Pop(SqStack &s, int &e)
{
if(s.top ==s.base ) printf("error2\n");
e=*--s.top ;
}//删除栈顶元素
void Print(SqStack s)
{
while(!StackEmpty(s))
{
int e;
Pop(s,e);
printf("%d ",e);
}
}//输出栈元素
void GetTop(SqStack s,int &e)
{
if(s.base ==s.top ) printf("error3\n");
e=*(s.top -1);
}//取栈顶元素
int StackLength(SqStack s)
{
return (s.top-s.base);
}
main()
{
int a;//存储栈顶元素
int b;//存储栈的长度
SqStack s;
InitStack(s);
Print( s);
GetTop(s,a);
b=StackLength(s);
printf("所取栈顶元素:%d\b",a);
printf("栈的长度:%d",b);
return 0;
}