/******************************************************
一个动态数组实现的简单栈
******************************************************/
#include<stdio.h>
#include<stdlib.h>
#define STACK_SIZE 100 /* 栈初始向量大小 */
#define STACKINCREMENT 10 /* 存储空间分配增量 */
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef struct sqstack
{
ElemType *bottom; /* 栈不存在时值为NULL */
ElemType *top; /* 栈顶指针 */
ElemType stacksize; /* 当前已分配空间,以元素为单位 */
}SqStack;
SqStack Init_Stack()
{
SqStack S;
S.bottom=(ElemType *)malloc(STACK_SIZE*(sizeof(ElemType)));
if(!S.bottom)
{
exit(ERROR);
}
S.top = S.bottom; /* 栈空时栈顶和栈底指针相同 */
S.stacksize = STACK_SIZE;
return S;
}
int push(SqStack *S,ElemType e)
{
if((*S).top-(*S).bottom >= (*S).stacksize-1) /* 栈满,追加存储空间 */
{
(*S).bottom=(ElemType *)realloc((*S).bottom,((*S).stacksize+STACKINCREMENT)*sizeof(ElemType));
if(!(*S).bottom)
{
return ERROR;
}
(*S).top=(*S).bottom+(*S).stacksize;
(*S).stacksize+=STACKINCREMENT;
}
*(*S).top=e;
(*S).top++;
return OK;
}
int pop(SqStack *S,ElemType *e) /*弹出栈顶元素*/
{
if((*S).top == (*S).bottom)
{
printf("1\n");
return ERROR; /* 栈空,返回失败标志 */
}
(*S).top--;
*e=*(*S).top;
return OK;
}
int main()
{
int tmp=0,i=0;
SqStack S;
S=Init_Stack();
for(i=0;i<10;i++)
{
push(&S,i);
}
for(i=0;i<10;i++)
{
pop(&S,&tmp);
printf("%d\n",tmp);
}
return 0;
}
一个动态数组实现的简单栈
最新推荐文章于 2024-07-15 11:03:37 发布