/*01 顺序栈的存储结构*/
Sqstack.h
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int ElemType;
typedef int Status;
typedef struct
{
ElemType data[MAXSIZE];
int top;
}Sqstack;
Status InitStack(Sqstack *S);/*初始化顺序栈*/
Status Push(Sqstack *S, ElemType e);/*压栈*/
Status Pop(Sqstack *S, ElemType *e);/*弹栈*/
void PrintStack(Sqstack s);/*打印栈中元素*/
Sqstack.c
Status InitStack(Sqstack *S)
{
S->top = -1;
return OK;
}
Status Push(Sqstack *S, ElemType e)
{
if(S->top == MAXSIZE-1)
{
return ERROR;
}
S->top++;
S->data[S->top] = e;
return OK;
}
Status Pop(Sqstack *S, ElemType *e)
{
if(S->top == -1)
{
return ERROR;
}
*e = S->data[S->top];
S->top--;
return OK;
}
void PrintStack(Sqstack s)
{
while(s->top != -1)
{
printf("%d ", s->data[s->top]);
s->top--;
}
printf("\n");
}
/*02 两栈共享空间 存储结构*/
SqDoubleStack.h
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int ElemType;
typedef int Status;
typedef struct
{
ElemType data[MAXSIZE ];
int top1;
int top2;
}SqDoubleStack;
SqDoubleStack.c
Status InitStack(SqDoubleStack *S)
{
S->top1 = -1;
S->top2 = MAXSIZE ;
return OK;
}
Status Push(SqDoubleStack *S, ElemType e, int stackNumber)
{
if(S->top1 + 1 == S->top2)
{
return ERROR;
}
if(1 == stackNumber)
{
S->top1++;
S->data[S->top1] = e;
}
else if(2 == stackNumber)
{
S->top2--;
S->data[S->top2] = e;
}
else;
return OK;
}
Status Pop(SqDoubleStack *S, ElemType *e, int stackNumber)
{
if(1 == stackNumber )
{
if(S->top1 == -1)
{
return ERROR;
}
else
{
*e = S->data[S->top1];
S->top1--;
}
}
else if(2 == stackNumber )
{
if(S->top2 == MAXSIZE )
{
return ERROR;
}
else
{
*e = S->data[S->top2];
S->top2++;
}
}
else;
}
void PrintStack(SqDoubleStack s, int stackNumber)
{
if(stackNumber == 1)
{
while(s.top1 != -1)
{
printf("%d ", s.data[s.top1]);
s.top1--;
}
printf("\n");
}
else if(stackNumber == 2)
{
while(s.top2 != MAXSIZE)
{
printf("%d ", s.data[s.top2]);
s.top2++;
}
printf("\n");
}
else;
}