#include <stdio.h>
#define STACK_SIZE 100 /*栈初始向量大小 */
#define STACK_INCREMENT 10 /* 空间分配增量 */
typedef int ElemType;
typedef int Status;
#define OK 1
#define ERROR -1
/* 栈的类型定义 */
typedef struct sqstack
{
ElemType *bottom; /* 栈不存在时未NULL */
ElemType *top; /* 栈顶指针 */
int stackSize; /* 当前已分配空间,已元素为单位 */
}*Pstack;
Status Init_Stack(Pstack S);
Status Push(Pstack S,ElemType e);
Status Pop(Pstack S,ElemType *e);
/* 栈的初始化 */
Status Init_Stack(Pstack S)
{
S->bottom=(ElemType *)malloc(STACK_SIZE *sizeof(ElemType));
if(!S->bottom) return ERROR;
S->top = S->bottom; /* 栈空时栈顶和栈底相同 */
S->stackSize = STACK_SIZE;
return OK;
}
/* 压栈(元素进栈)*/
Status Push(Pstack S,ElemType e)
{
if(S->top-S->bottom >=S->stackSize-1)
{
S->bottom = (ElemType *)realloc(S->bottom,(STACK_INCREMENT+STACK_SIZE)*sizeof(ElemType));
/* 栈满追加存储空间 */
if(!S->bottom) return ERROR;
S->top = S->bottom+S->stackSize-1;
S->stackSize += STACK_INCREMENT;
}
*(S->top) = e; S->top++; /* 栈顶指针加1, e成为新的栈顶*/
return OK;
}
/* 弹栈(元素出栈)*/
Status Pop(Pstack S,ElemType *e)
{
if(S->top == S->bottom)
{
return ERROR; /* 栈空,返回失败标记 */
}
S->top--;
*e = *(S->top);
return OK;
}
int main(void)
{
int i =0,j=0;
Pstack stack;
Init_Stack(stack);
while(i<10)
{
ElemType e = i;
Push(stack,e);
i++;
}
while(j<10)
{
ElemType e1;
Pop(stack,&e1);
printf("%d,",e1);
j++;
}
return 0;
}
以上代码是纯c语言,我是在code::blocks上执行通过的。大家可以参考。