#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
//建立顺序栈
#define STACK_INIT_SIZE 100
#define STACKINCRESEMENT 10
typedef int DataType ;
typedef struct SqStack
{
DataType *base;
DataType *top;
int stacksize;
}SqStack,* pSqStack;
pSqStack InitStack()
{
pSqStack s=(pSqStack) malloc(sizeof(SqStack));
if(! s)
return NULL;
s->base=(DataType *) malloc(sizeof(DataType) *STACK_INIT_SIZE);
if(! s->base)
exit(-1);
s->top=s->base;
s->stacksize=STACK_INIT_SIZE;
return s;
}
DataType GetTop(pSqStack s)
{
if( !s)
{
printf("the stack initialization failed \n");
exit(-1);
}
if(s->base==s->top)
{
printf("the stack is null\n");
return 0;
}
return *(s->top-1);
// return *(--s->top);
// return s->base[--s->top];
}
int IsStackEmpty(pSqStack s)
{
if( !s)
{
printf("the stack initialization failed \n");
exit(-1);
}
if(s->base==s->top)
{
return 1;
}
return 0;
}
void Push( pSqStack s,DataType x)
{
if( (s->top-s->base) >=s->stacksize)
{
s->base=(DataType *) realloc( s->base,(STACK_INIT_SIZE+STACKINCRESEMENT)*sizeof(DataType) ) ;
if( !s->base)
exit(-1);
s->top=s->base + s->stacksize;
s->stacksize+=STACKINCRESEMENT;
}
* s->top=x;
s->top++;
}
void Pop(pSqStack s,DataType *x)
{
if(s->base==s->top)
printf("the stack is null,can't pop anything\n");
// *x=s->base[--s->top];
if(x!=NULL) // 为了和栈清空结合起来
*x= *(--s->top);
else
--s->top;
}
int GetStackSize(pSqStack s)
{
if(!s)
exit(-1);
return s->stacksize;
}
void ClearStack(pSqStack s)
{
if(!s)
exit(-1);
while(s->base !=s->top) //或者 while( !IsSatckEmpty(s))
{
Pop(s, NULL);
}
}
void DestroyStack(pSqStack s)
{
if( !s)
exit(-1);
free(s->base);
free(s);
}
void Visit(DataType data)
{
printf("%d ",data);
}
void StackTraverse(pSqStack s)
{
DataType *topsave=s->top; //遍历后top指针要还原到原先位置
DataType data;
while(s->base!=s->top)
{
Pop(s,&data);
Visit(data);
}
s->top=topsave;
}
int main()
{
pSqStack s=InitStack();
char i;
printf("gettop :\n");
for( i=0 ;i<105;i++)
{
Push(s,i);
DataType datatop= GetTop(s);
printf("%d ",datatop);
}
printf("\nIsStackEmpty %d",IsStackEmpty(s) );
printf("\n traverse the stack:\n");
StackTraverse(s);
printf("\n the current stack' size :%d\n",GetStackSize(s) );
DataType data;
Pop(s,&data);
printf("Pop %d \n",data);
printf("\n the current stack' size :%d\n",GetStackSize(s) );
Pop(s,&data);
printf("Pop %d \n",data);
printf("stack clear!\n");
ClearStack(s);
printf("stack destroy!\n");
DestroyStack(s);
}
顺序栈的实现SqStack
最新推荐文章于 2023-01-19 22:24:30 发布