#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* pArr;
int capacity;
int top;
}ST, *pST;
void Stack_Init(pST pstack);
void Stack_Push(pST pstack, STDataType pvalue);
void Stack_Pop(pST pstack);
int Stack_Size(pST pstack);
bool Stack_IsEmpty(pST pstack);
STDataType Stack_Top(pST pstack);
void Stack_Destory(pST pstack);
void Stack_Print(ST stack);
#include "stack.h"
void Stack_Init(pST pstack)
{
assert(pstack);
pstack->pArr = (STDataType*)malloc(sizeof(STDataType)*4);
if(pstack->pArr == NULL)
{
printf("malloc failed!");
exit(-1);
}
pstack->capacity = 4;
pstack->top = 0;
}
void Stack_Push(pST pstack, STDataType value)
{
assert(pstack);
if(pstack->top == pstack->capacity)
{
STDataType* enlarged = (STDataType*)realloc(pstack->pArr, sizeof(STDataType)*2*pstack->capacity);
pstack->pArr = enlarged;
pstack->capacity *= 2;
}
pstack->pArr[pstack->top] = value;
pstack->top++;
}
void Stack_Pop(pST pstack)
{
assert(pstack);
if(Stack_IsEmpty(pstack))
{
printf("Stack is empty");
}
else
pstack->top--;
}
int Stack_Size(pST pstack)
{
return pstack->top;
}
bool Stack_IsEmpty(pST pstack)
{
assert(pstack);
if(pstack->top == 0)
{
return true;
}
else
return false;
}
STDataType Stack_Top(pST pstack)
{
assert(pstack);
assert(pstack->top > 0);
return pstack->pArr[pstack->top - 1];
}
void Stack_Destory(pST pstack)
{
assert(pstack);
free(pstack->pArr);
pstack->pArr = NULL;
pstack->capacity = 0;
pstack->top = 0;
}
int main()
{
ST stack;
Stack_Init(&stack);
Stack_Push(&stack, 1);
Stack_Push(&stack, 2);
Stack_Push(&stack, 3);
Stack_Push(&stack, 4);
Stack_Push(&stack, 5);
Stack_Push(&stack, 6);
Stack_Push(&stack, 7);
while (!Stack_IsEmpty(&stack))
{
printf("%d ", Stack_Top(&stack));
Stack_Pop(&stack);
}
printf("\n");
Stack_Destory(&stack);
return 0;
}