Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,849 questions

55,678 answers

573 users

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 May 13 by avibootz
...