#define STACK_SIZE 100 /* 栈初始向量大小 */
#define STACKINCREMENT 10 /* 存储空间分配增量 */
#typedef int ElemType ;
typedef struct sqstack
{
ElemType *bottom; /* 栈不存在时值为NULL */
ElemType *top; /* 栈顶指针 */
int stacksize ; /* 当前已分配空间,以元素为单位 */
}SqStack ;
2 栈的初始化
Status Init_Stack(void)
{
SqStack S ;
S.bottom=(ElemType *)malloc(STACK_SIZE *sizeof(ElemType));
if (! S.bottom) return ERROR;
S.top=S.bottom ; /* 栈空时栈顶和栈底指针相同 */
S. stacksize=STACK_SIZE;
return OK ;
}
3 压栈(元素进栈)
Status push(SqStack S , ElemType e)
{
if (S.top-S.bottom>=S. stacksize-1)
{
S.bottom=(ElemType *)realloc((S. STACKINCREMENT+STACK_SIZE) *sizeof(ElemType));
/* 栈满,追加存储空间 */
if (! S.bottom) return ERROR;
S.top=S.bottom+S. stacksize ;
S. stacksize+=STACKINCREMENT ;
}
*S.top=e;
S.top++ ; /* 栈顶指针加1,e成为新的栈顶 */
return OK;
}
4 弹栈(元素出栈)
Status pop( SqStack S, ElemType *e )
/*弹出栈顶元素*/
{
if ( S.top== S.bottom )
return ERROR ; /* 栈空,返回失败标志 */
S.top-- ;
e=*S. top ;
return OK ;
}
栈的静态顺序存储表示
1 栈的类型定义
# define MAX_STACK_SIZE 100 /* 栈向量大小 */
# typedef int ElemType ;
typedef struct sqstack
{
ElemType stack_array[MAX_STACK_SIZE] ;
int top;
}SqStack ;
2 栈的初始化
SqStack Init_Stack(void)
{
SqStack S ;
S.top=0 ;
return(S) ;
}
3 压栈(元素进栈)
Status push(SqStack S , ElemType e)
/* 使数据元素e进栈成为新的栈顶 */
{
if (S.top==MAX_STACK_SIZE-1) return ERROR; /* 栈满,返回错误标志 */
S.top++ ; /* 栈顶指针加1 */
S.stack_array[S.top]=e ; /* e成为新的栈顶 */
return OK; /* 压栈成功 */
}
4 弹栈(元素出栈)
Status pop( SqStack S, ElemType *e )
/*弹出栈顶元素*/
{
if ( S.top==0 ) return ERROR ; /* 栈空,返回错误标志 */
*e=S.stack_array[S.top] ;
S.top-- ;
return OK ;
}