#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 6
#define STACK_INCREMENT 5
#define OVERFLOW 0
#define FALSE 0
#define TRUE 1
#define ERROR -1
#define OK 0
typedef int SElemType;
typedef int Status;
struct SqStack
{
SElemType *base;
SElemType *top;
int stacksize;
};
void InitStack(SqStack &S)
{
S.base = (SElemType *)malloc(sizeof(SElemType) * STACK_INIT_SIZE);
if(!S.base)
exit(0);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
void DestroyStack(SqStack &S)
{
free(S.base);
S.top = S.base = NULL;
S.stacksize = 0;
}
void ClearStack(SqStack &S)
{
S.top = S.base;
}
Status StackEmpty(SqStack S)
{
if(S.top == S.base)
return TRUE;
else
return FALSE;
}
Status StackFull(SqStack S)
{
if(S.top - S.base == S.stacksize)
return TRUE;
else
return FALSE;
}
int StackLength(SqStack S)
{
return S.top - S.base;
}
void Push(SqStack &S, SElemType e)
{
if(StackFull(S))
{
S.base = (SElemType *)realloc(S.base, (S.stacksize + STACK_INCREMENT) * sizeof(SElemType));
if(!S.base)
exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += STACK_INCREMENT;
}
*S.top++ = e;
}
Status Pop(SqStack &S, SElemType &e)
{
if(StackEmpty(S))
return ERROR;
e = *--S.top;
return OK;
}
Status GetTop(SqStack S, SElemType &e)
{
if(StackEmpty(S))
return ERROR;
else
{
e = *(S.top - 1);
return OK;
}
}
void print(SElemType e)
{
printf("%d ", e);
}
void StackTraverse(SqStack S, void(*visit)(SElemType))
{
while(S.top > S.base)
visit(*S.base++);
printf("\n");
}
int main()
{
SqStack S;
InitStack(S);
Push(S, 1);
Push(S, 2);
Push(S, 3);
Push(S, 4);
Push(S, 5);
Push(S, 6);
Push(S, 111);
StackTraverse(S, print);
SElemType e = 0;
GetTop(S, e);
printf("top = %d\n",e);
int len = StackLength(S);
printf("len = %d\n", len);
for(int i = 0; i < len; i++)
{
if(Pop(S, e) == OK)
{
printf("%d ", e);
}
else
printf("ERROR!\n");
}
printf("\n");
StackTraverse(S, print);
return 0;
}
C语言顺序栈
最新推荐文章于 2022-03-31 23:52:23 发布