How to implement a linked‑list stack with dynamic size and no fixed limit in C

1 Answer

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

/* Node in the linked list */
typedef struct Node {
    int value;
    struct Node *next;
} Node;

/* Stack represented by pointer to top node */
typedef struct {
    Node *top;
} Stack;

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

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

/* Push value onto stack */
bool stack_push(Stack *s, int value) {
    Node *n = malloc(sizeof(Node));
    if (!n)
        return false;   /* allocation failed */

    n->value = value;
    n->next = s->top;
    s->top = n;
    
    return true;
}

/* Pop value from stack */
bool stack_pop(Stack *s, int *out) {
    if (stack_empty(s))
        return false;

    Node *n = s->top;
    *out = n->value;
    s->top = n->next;
    free(n);
    
    return true;
}

/* Peek at top value */
bool stack_peek(Stack *s, int *out) {
    if (stack_empty(s))
        return false;

    *out = s->top->value;
    
    return true;
}

/* Print stack (top → bottom) */
void stack_print(Stack *s) {
    printf("Stack (top → bottom): ");
    for (Node *n = s->top; n != NULL; n = n->next)
        printf("%d ", n->value);
    printf("\n");
}

/* Free all nodes */
void stack_clear(Stack *s) {
    Node *n = s->top;
    while (n) {
        Node *next = n->next;
        free(n);
        n = next;
    }
    s->top = NULL;
}

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);

    stack_clear(&s);
    
    return 0;
}



/* 
run:

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

*/

 



answered 27 minutes ago by avibootz
...