#include
#include
#include
#define DEFAULT_SIZE 8
#define INCREMENT 8
#define STACK_OVERFLOW -100
#define BAD_ALLOC -101
typedef int T;
typedef struct stack {
T* data;
size_t capacity;
size_t count;
} Stack;
static Stack* create() {
Stack* head = NULL;
head = malloc(sizeof(Stack));
if (head == NULL) {
exit(BAD_ALLOC);
}
head->capacity = DEFAULT_SIZE;
head->data = malloc(head->capacity * sizeof(T));
if (head->data == NULL) {
free(head);
exit(BAD_ALLOC);
}
head->count = 0;
return head;
}
static void claer(Stack** stack) {
free((*stack)->data);
free(*stack);
*stack = NULL;
}
static void resize(Stack* stack) {
stack->capacity += INCREMENT;
stack->data = realloc(stack->data, stack->capacity * sizeof(T));
if (stack->data == NULL) {
exit(STACK_OVERFLOW);
}
}
static void push(Stack* stack, T value) {
if (stack->count >= stack->capacity) {
resize(stack);
}
stack->data[stack->count] = value;
stack->count++;
}
static _Bool empty(Stack* stack) {
return stack->count == 0;
}
static void pop(Stack* stack) {
stack->count--;
}
static T top(const Stack* stack) {
return stack->data[stack->count - 1];
}
static void shrink_to_fit(Stack* stack) {
stack->capacity = stack->count;
stack->data = realloc(stack->data, stack->capacity * sizeof(T));
}
static size_t size(Stack* stack) {
return stack->count;
}
static size_t capacity(Stack* stack) {
return stack->capacity;
}
int main(void) {
int box[] = { 25, 47, 13, 84, 66, 89, 18, 33, 58, 62, 85 };
size_t length = sizeof(box) / sizeof(box[0]);
size_t i = 0;
Stack* stack = create();
while (i != length) {
push(stack, box[i]);
printf("data: %d, count: %zu, capacity: %zu\n",
top(stack),
size(stack),
capacity(stack)
);
++i;
}
puts("----------------------------------");
while (!empty(stack)) {
printf("data: %d, count: %zu, capacity: %zu\n",
top(stack),
size(stack),
capacity(stack)
);
pop(stack);
if (size(stack) == 4) {
shrink_to_fit(stack);
}
}
claer(&stack);
return 0;
}
Пользуйтесь!