Head.H
#define N 5
typedef struct _stack
{
int *base;
int *top;
int stacksize;
}Sta, *sta;
sta InitStack(int stacksize);
int IsEmpty(sta S);
int IsFull(sta S);
void PushStack(sta S, int val);
int GetStackTop(sta S);
int PopStack(sta S);
void PrintStack(sta S);
Function.C
sta InitStack(int stacksize)
{
sta S;
S = (sta)malloc(sizeof(Sta));
S->base = (int*)malloc(stacksize * sizeof(int));
S->top = S->base;
S->stacksize = stacksize;
return S;
}
int IsEmpty(sta S)
{
if (S->top == S->base)
{
return 1;
}
}
int IsFull(sta S)
{
if ((S->top - S->base) == S->stacksize)
{
return 1;
}
}
void PushStack(sta S, int val)
{
if (IsFull(S) == 1)
{
S->base = (int*)realloc(S->base, (S->stacksize + 10) * sizeof(int));
S->top = S->base + S->stacksize;
S->stacksize += 10;
}
*(S->top) = val;
S->top++;
}
int GetStackTop(sta S)
{
return *(S->top - 1);
}
int PopStack(sta S)
{
if (IsEmpty(S) == 1)
{
printf("The stack is nothing left! \n");
return;
}
S->top--;
int temp = *(S->top);
return temp;
}
void PrintStack(sta S)
{
int *temp = S->base;
while (temp != S->top)
{
printf("%d ", *temp);
temp++;
}
printf("\n");
}
Main.C
void main(void)
{
sta S = InitStack(5);
for (int i = 0; i < 6; i++)
{
PushStack(S, i);
}
PrintStack(S);
int topdata = GetStackTop(S);
printf("%d \n", topdata);
int recdata = PopStack(S);
PrintStack(S);
printf("%d \n", recdata);
system("pause");
}