#include<stdio.h>
#include<stdlib.h>
#include<assert.h>// if false,break all the things
typedef struct sqStack
{
int *base; //base point
int *top; //top point
int stack_Size;
}sqStack;
//1.traverse all the stack
void print_stack(sqStack*s)
{
assert(s); //if s is true
int *num = s->base;//using the point
if (s->base == s->top) {
printf("this is a empty stack!");
}
for (num; num != s->top; num++)
{
printf("the num is %2d", *num);
printf("\n");
}
}
//init_Stack
sqStack*init_Stack(sqStack*s) {
s = (sqStack*)malloc(sizeof(sqStack));//assign the room
if (!s)
{
exit(0);
}
s->base = (int*)malloc(STACK_INIT_SIZE * sizeof(int));//assign the num
s->top = s->base;
s->stack_Size = STACK_INIT_SIZE;
printf("Init the stack sucessfully!\n");
return s;
}
//Free_stack
int Free_stack(sqStack*s) {
if (!s)
{
printf("Stack is no need to free");
return 0;
}
else
{
free(s->base);
free(s);
return 1;
}
}
//push data to stack
int push_stack(sqStack*s, int e) {
assert(s);
//(if the stack is full ,assign the room automaticly)
if (s->top - s->base >= s->stack_Size) //the stack is full
{
s->base = (int*)realloc(s->base, (s->stack_Size + 2)*sizeof(int));//the int is 2 byte
if (!s->base)
{
printf("realloc false\n");
return 0;
}
s->top = s->base + s->stack_Size;
s->stack_Size += 2;
}
*(s->top) = e;
++(s->top);
return 1;
}
int pop_stack(sqStack*s)
{
assert(s);
if (s->base == s->top) {
printf("it is a empty stack\n");
return 0;
}
printf("the pop data is %2d\n",*((s->top)-1));
--(s->top);
return 1;
}
void main()
{
int i;
sqStack *s;
s = init_Stack(&s);
for (i = 0; i < 20; i++)
{
int num = rand() % 100;
push_stack(s, num);
}
print_stack(s);
printf("*************************************begin to pop stack***************************************\n");
pop_stack(s);
print_stack(s);
Free_stack(s);
system("pause");
}