How to implement a stack in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>

#define STACK_MAX 128

/* Stack structure */
typedef struct {
    int data[STACK_MAX];
    int top;                /* index of the top element */
} Stack;

/* Initialize the stack */
void stack_init(Stack *s) {
    s->top = -1;            /* empty stack */
}

/* Check if empty */
bool stack_empty(Stack *s) {
    return s->top == -1;
}

/* Check if full */
bool stack_full(Stack *s) {
    return s->top == STACK_MAX - 1;
}

/* Push value onto stack */
bool stack_push(Stack *s, int value) {
    if (stack_full(s))
        return false;       /* overflow */
    s->data[++s->top] = value;
    
    return true;
}

/* Pop value from stack */
bool stack_pop(Stack *s, int *out) {
    if (stack_empty(s))
        return false;       /* underflow */
    *out = s->data[s->top--];
    
    return true;
}

/* Peek at top value */
bool stack_peek(Stack *s, int *out) {
    if (stack_empty(s))
        return false;
    *out = s->data[s->top];
    
    return true;
}

/* Print stack (top → bottom) */
void stack_print(Stack *s) {
    printf("Stack (top → bottom): ");
    for (int i = s->top; i >= 0; i--)
        printf("%d ", s->data[i]);
    printf("\n");
}

int main(void) {
    Stack s;
    stack_init(&s);

    stack_push(&s, 10);
    stack_push(&s, 20);
    stack_push(&s, 30);
    stack_push(&s, 40);
    stack_push(&s, 50);

    stack_print(&s);

    int x;
    stack_pop(&s, &x);
    printf("Popped: %d\n", x);

    stack_print(&s);

    return 0;
}


/* 
run:

Stack (top → bottom): 50 40 30 20 10 
Popped: 50
Stack (top → bottom): 40 30 20 10 

*/

 



answered 36 minutes ago by avibootz
...