C Data Structures : Dynamic Stack Sample

#include <stdlib.h>
#include <stdio.h>


struct stack_node {
    int val;
    struct stack_node * previous;
};
typedef struct stack_node stack_node_t;

struct stack {
    int size;
    stack_node_t *head;
};

typedef struct stack stack_t;

void init_stack(stack_t *stack) {
    stack->size = 0;
    stack->head = (void*)0;
}

void push(stack_t *stack, int val){
    stack_node_t *node = malloc(sizeof(stack_node_t)*1); // create new node
    node->previous = stack->head;
    stack->head = node; // head asign last node
    node->val = val;
    stack->size++;
}


int pop(stack_t *stack) {
    if(stack->size == 0) {
        return -1;
    }
    stack_node_t *last_node = stack->head;
    int result = last_node->val;
    stack->head = last_node->previous;
    free(last_node);
    stack->size--;
    return result;
}


int main() {
    stack_t my_stack;
    init_stack(&my_stack);
    push(&my_stack, 5);
    push(&my_stack, 3);
    push(&my_stack, 2);
    printf("%d\n",pop(&my_stack));
    printf("%d\n",pop(&my_stack));
    printf("%d\n",pop(&my_stack));
    printf("%d\n",pop(&my_stack));
    printf("%d\n",pop(&my_stack));

}

Leave a Reply

Your email address will not be published. Required fields are marked *