顺序栈
代码来自:大话数据结构
#define MAXSIZE 20
typedef int Status;
typedef int SElemType;
typedef struct
{
SElemType data[MAXSIZE];
int top;
}SqStack;
int StackLength(SqStack S)
{
return S.top+1;
}
Status GetTop(SqStack S,SElemType *e)
{
if (S.top==-1)
return ERROR;
else
*e=S.data[S.top];
return OK;
}
Status Push(SqStack *S,SElemType e)
{
if(S->top == MAXSIZE -1)
{
return ERROR;
}
S->top++;
S->data[S->top]=e;
return OK;
}
Status Pop(SqStack *S,SElemType *e)
{
if(S->top==-1)
return ERROR;
*e=S->data[S->top];
S->top--;
return OK;
}
int main()
{
int j;
SqStack s;
int e;
if(InitStack(&s)==OK)
for(j=1;j<=10;j++)
Push(&s,j);
printf("栈中元素依次为:");
StackTraverse(s);
Pop(&s,&e);
printf("弹出的栈顶元素 e=%d\n",e);
printf("栈空否:%d(1:空 0:否)\n",StackEmpty(s));
GetTop(s,&e);
printf("栈顶元素 e=%d 栈的长度为%d\n",e,StackLength(s));
ClearStack(&s);
printf("清空栈后,栈空否:%d(1:空 0:否)\n",StackEmpty(s));
return 0;
}
共享栈
typedef int Status;
typedef int SElemType;
typedef struct
{
SElemType data[MAXSIZE];
int top1;
int top2;
}SqDoubleStack;
int StackLength(SqDoubleStack S)
{
return (S.top1+1)+(MAXSIZE-S.top2);
}
Status Push(SqDoubleStack *S,SElemType e,int stackNumber)
{
if (S->top1+1==S->top2)
return ERROR;
if (stackNumber==1)
S->data[++S->top1]=e;
else if (stackNumber==2)
S->data[--S->top2]=e;
return OK;
}
Status Pop(SqDoubleStack *S,SElemType *e,int stackNumber)
{
if (stackNumber==1)
{
if (S->top1==-1)
return ERROR;
*e=S->data[S->top1--];
}
else if (stackNumber==2)
{
if (S->top2==MAXSIZE)
return ERROR;
*e=S->data[S->top2++];
}
return OK;
}
递归