data-structures · intermediate · ~15 min

Int stack (push/pop/peek)

Implement a dynamic array used as a LIFO stack.

Challenge

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;

Task

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.

Input

Operations are driven by the grader: a sequence of pushes, pops, and peeks. pop/peek may be called on an empty stack.

Output

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.

Example

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

Edge cases

  • pop/peek on an empty stack return -1 and do not touch *out-dependent logic.
  • Pushing many values must grow capacity (e.g. by doubling).

Rules

  • Use malloc/realloc/free; stack_free must reset len and cap to 0.

Input format

An istack_t pointer plus per-call args (value to push, or out pointer for pop/peek).

Output format

Status codes: 0 on success, -1 on empty (pop/peek) or allocation failure (push); values via out.

Constraints

Use malloc/realloc/free; stack_free resets len and cap to 0; LIFO order.

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.