data-structures · intermediate · ~15 min
Implement a dynamic array used as a LIFO stack.
Given the supplied struct
typedef struct { int *data; size_t cap, len; } istack_t;
implement:
void stack_init(istack_t *s)void stack_free(istack_t *s)int stack_push(istack_t *s, int v) — grow if needed, return 0 on successint stack_pop(istack_t *s, int *out) — return 0 on success, -1 on emptyint stack_peek(const istack_t *s, int *out) — return 0 on success, -1 on emptyAll allocations use malloc/realloc/free.
#include <stdlib.h>
#include <stddef.h>
void stack_init(istack_t *s){ /* TODO */ }
void stack_free(istack_t *s){ /* TODO */ }
int stack_push(istack_t *s, int v){ /* TODO */ return -1; }
int stack_pop (istack_t *s, int *out){ /* TODO */ return -1; }
int stack_peek(const istack_t *s, int *out){ /* TODO */ return -1; }
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.