用一维数组模拟的顺序栈:
#include "declear.h"
#include "stdio.h"
#define MAXSIZE 10
typedef struct
{
SElemType data[MAXSIZE];
int top;
}SqStack;
Status InitStack(SqStack *S)
{
S->top = -1;
return OK;
}
Status Visit(SElemType elem)
{
printf("%d\n",elem);
return OK;
}
Status StackTraverse(SqStack S)
{
int index = 0;
while (index <= S.top)
{
Visit(S.data[index]);
++index;
}
//printf("\n");
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;
}
Status ClearStack(SqStack *S)
{
(*S).top = -1;
return OK;
}
int StackLength(SqStack S)
{
return S.top + 1;
}
Status GetTop(SqStack S, SElemType *elem)
{
if (-1 == S.top)
{
return ERROR;
}
else
{
*elem = S.data[S.top];
return OK;
}
}
Status EmptyStack(SqStack S)
{
if (-1 == S.top)
{
return TRUE;
}
else
{
return FALSE;
}
}
int main ()
{
SqStack stack;
SElemType elem;
if (InitStack(&stack) )
{
for (int index = 0; index < MAXSIZE; index++)
{
Push(&stack, index);
}
}
printf("length = %d\n", StackLength(stack));
printf("The stack is :\n");
StackTraverse(stack);
printf("Test of Pop :\n");
Pop(&stack, &elem);
printf("elem = %d\n", elem);
printf("Test of GetTop :\n");
GetTop(stack, &elem);
printf("elem = %d\n", elem);
return 0;
}