dynamic_array_stack.h
#pragma once
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
typedef int E;
typedef struct {
E* elements;
int size;
int capacity;
}Stack;
Stack* create_stack();
void destroy_stack(Stack* s);
void push_stack(Stack* s, E val);
int pop_stack(Stack* s);
int peek_stack(Stack* s);
bool is_empty(Stack * s);
dynamic_array_stack.c
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#include"dynamic_array_stack.h"
#define THRESHOLD 1024
#define default_capacity 10
Stack* create_stack() {
Stack* stack = malloc(sizeof(Stack));
if (stack == NULL) {
printf("ERROR:malloc failed in create_stack\n");
return NULL;
}
stack->size = 0;
stack->capacity = default_capacity;
stack->elements = malloc(default_capacity * sizeof(E));
if (stack->elements = NULL) {
free(stack);
printf("ERROR:malloc failed in create_stack");
return NULL;
}
return stack;
}
void destroy_stack(Stack* s) {
free(s->elements);
free(s);
}
void grow_capacity(Stack* s) {
int new_capacity =
s->capacity >= THRESHOLD ?
(s->capacity + (s->capacity >> 1)) :
(s->capacity << 1);
E* new_arr = realloc(s->elements, sizeof(E) * new_capacity);
if (new_arr == NULL) {
printf("realloc failed in grow_capacity\n");
exit(1);
}
s->elements = new_arr;
s->capacity = new_capacity;
}
void push_stack(Stack* s, E val) {
if (s->capacity == s->size) {
grow_capacity(s);
}
s->elements[s->size] = val;
s->size++;
}
E pop_stack(Stack* s) {
if (is_empty) {
printf("ERROR:the stack is empty,pop_stack failed");
exit(1);
}
return s->elements[--s->size];
}
E peek_stack(Stack* s) {
if (is_empty) {
printf("ERROR:the stack is empty,peek_stack failed");
exit(1);
}
return s->elements[s->size-1];
}
bool is_empty(Stack* s) {
return s->size == 0;
}