</>EmbeddedInterview

Implement two stacks in one array.

Easy"Coding: Linked Lists, Stacks & Queues"
#include <stdbool.h>

#define CAP 16
typedef struct { int a[CAP]; int top1, top2; } two_stacks_t;   /* top1 = -1, top2 = CAP initially */

void ts_init(two_stacks_t *s) { s->top1 = -1; s->top2 = CAP; }
bool ts_push1(two_stacks_t *s, int v) { if (s->top1 + 1 == s->top2) return false; s->a[++s->top1] = v; return true; }
bool ts_push2(two_stacks_t *s, int v) { if (s->top1 + 1 == s->top2) return false; s->a[--s->top2] = v; return true; }
bool ts_pop1(two_stacks_t *s, int *v) { if (s->top1 < 0) return false; *v = s->a[s->top1--]; return true; }
bool ts_pop2(two_stacks_t *s, int *v) { if (s->top2 == CAP) return false; *v = s->a[s->top2++]; return true; }

Points: grow one stack from each end towards the middle; the array is full only when the tops meet, so space is shared efficiently (better than splitting it in half). The same idea is the classic heap-grows-up / stack-grows-down memory layout.