data-structures · intermediate · ~15 min

Int stack (push/pop/peek)

Implement a dynamic array used as a LIFO stack.

Challenge

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 success
  • int stack_pop(istack_t *s, int *out) — return 0 on success, -1 on empty
  • int stack_peek(const istack_t *s, int *out) — return 0 on success, -1 on empty

All allocations use malloc/realloc/free.

Starter code

#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.