data-structures · intermediate · ~15 min
Implement a dynamic array used as a LIFO stack.
Build a growable LIFO stack of ints backed by a dynamic array.
The grader supplies this struct:
typedef struct { int *data; size_t cap, len; } istack_t;
Implement these functions (no main — the grader calls them):
void stack_init(istack_t *s) — set up an empty stack.void stack_free(istack_t *s) — free storage and reset the fields.int stack_push(istack_t *s, int v) — push v, growing capacity if needed; return 0 on success, -1 on allocation failure.int stack_pop(istack_t *s, int *out) — remove the top into *out; return 0, or -1 if empty.int stack_peek(const istack_t *s, int *out) — copy the top into *out without removing it; return 0, or -1 if empty.Operations are driven by the grader: a sequence of pushes, pops, and peeks. pop/peek may be called on an empty stack.
Each function returns its status code (see above). pop/peek write the relevant value through out only on success. Values come out in last-in-first-out order.
push 1, push 2, push 3
peek -> out=3, returns 0
pop -> out=3, returns 0
pop -> out=2, returns 0
pop on empty -> returns -1
pop/peek on an empty stack return -1 and do not touch *out-dependent logic.malloc/realloc/free; stack_free must reset len and cap to 0.An istack_t pointer plus per-call args (value to push, or out pointer for pop/peek).
Status codes: 0 on success, -1 on empty (pop/peek) or allocation failure (push); values via out.
Use malloc/realloc/free; stack_free resets len and cap to 0; LIFO order.
#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.