Stack<T> (LIFO)

Arrays and collections

//C has no stack: an array and the number of items in it
constexpr int stackSize = 16;

typedef struct {
    int items[stackSize];
    int count;
} Stack;

bool push(Stack *stack, int value) {
    if (stack->count == stackSize) {
        return false; //the stack is full
    }
    stack->items[stack->count++] = value;
    return true;
}

//the caller checks that the stack is not empty
int peek(const Stack *stack) {
    return stack->items[stack->count - 1];
}

int pop(Stack *stack) {
    return stack->items[--stack->count];
}

Stack intStack = {};
push(&intStack, 1);
push(&intStack, 3);
push(&intStack, 5);

int top = peek(&intStack);
//top is 5
int first = pop(&intStack);
//first is 5
int second = pop(&intStack);
//second is 3
int third = pop(&intStack);
//third is 1
bool isEmpty = intStack.count == 0;
//isEmpty is true

printf("top is %d\n", top);
printf("first is %d\n", first);
printf("second is %d\n", second);
printf("third is %d\n", third);
printf("isEmpty is %s\n", isEmpty ? "true" : "false");