stack Algorithm

The stack using a doubly linked list (DLL) algorithm is a dynamic data structure that stores a collection of elements in a linear fashion, where each element has a reference to the element before and after it. This stack allows for the efficient management of elements by performing insertions and deletions at the beginning or end of the list without affecting the rest of the elements. A commonly used analogy to describe a stack is a stack of plates, where you can only add or remove a plate from the top of the stack. This behavior is known as Last-In, First-Out (LIFO), which means that the most recently added element is always the first one to be removed. Implementing a stack using a doubly linked list offers several advantages over other data structures like arrays. First, it allows for dynamic resizing, which means that the stack can grow or shrink in size as elements are added or removed. This makes it more memory-efficient, as the stack only uses the exact amount of memory needed to store its elements. Second, the time complexity for inserting and deleting elements in a DLL-based stack is O(1), which makes these operations quite fast. However, this comes at the cost of increased complexity in managing the pointers for the previous and next elements in the list, which can make the implementation more challenging than using an array-based stack.
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"

#define T Stack_T

typedef struct elem {
    void *val;
    struct elem *next;
} elem_t;

struct T {
    int count;
    elem_t *head;
};

/* Initial stack */
T Stack_init (void) {
    T stack;
    stack = (T) malloc(sizeof(T));
    stack->count = 0;
    stack->head = NULL;
    return stack;
}

/* Check empty stack*/
int Stack_empty(T stack) {
    assert(stack);
    return stack->count == 0;
}

/* Return size of the stack */
int Stack_size(T stack) {
    assert(stack);
    return stack->count;
}

/* Push an element into the stack */
void Stack_push(T stack, void *val) {
    elem_t *t;

    assert(stack);
    t = (elem_t *) malloc(sizeof(elem_t));
    t->val = val;
    t->next = stack->head;
    stack->head = t;
    stack->count++;
}

/* Pop an element out of the stack */
void *Stack_pop(T stack) {
    void *val;
    elem_t *t;

    assert(stack);
    assert(stack->count > 0);
    t = stack->head;
    stack->head = t->next;
    stack->count--;
    val = t->val;
    free(t);
    return val;
}

/* Print all elements in the stack */
void Stack_print(Stack_T stack) {
    assert(stack);

    int i, size = Stack_size(stack);
    elem_t *current_elem = stack->head;
    printf("Stack [Top --- Bottom]: ");
    for(i = 0; i < size; ++i) {
        printf("%p ", (int *)current_elem->val);
        current_elem = current_elem->next;
    }
    printf("\n");
}

LANGUAGE:

DARK MODE: