Skip to content

Commit

Permalink
feat: add stack implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Silva97 committed Jan 19, 2025
1 parent 8ed2168 commit 9fe6933
Show file tree
Hide file tree
Showing 3 changed files with 106 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/include/stack.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#pragma once

#include <stdbool.h>

#include "types/err.h"
#include "types/stack.h"

/**
* Initializes the given stack.
*
* @param stack The stack to be initialized.
*/
void
stack_init(stack_t* stack);

/**
* Push a new value on the stack.
*
* @param stack The stack where tbe value will be pushed.
* @param value The value to push on the stack.
*
* @return The index of the new value inside the stack.
*/
unsigned int
stack_push(stack_t* stack, void* value);

/**
* Pop a value from the stack.
*
* @param stack The stack from where the value will be poped.
* @param value Pointer for where the poped value will be saved.
*
* @return ERR_EMPTY on stack is empty.
* @return ERR_OK on value is poped successful.
*/
error_code_t
stack_pop(stack_t* stack, void** value);

/**
* Check if the given stack is empty.
*
* @param stack The stack to check.
*
* @return true on stack is empty.
* @return false if stack has values.
*/
bool
stack_isempty(stack_t* stack);
14 changes: 14 additions & 0 deletions src/include/types/stack.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#pragma once

#define STACK_INITIAL_LENGTH 20
#define STACK_LENGTH_INCREMENT 50

/**
* A struct representing a dynamic stack. Each value on the stack is a `void *`.
*/
typedef struct stack
{
void** values; ///< Array of values on the stack.
unsigned int length; ///< Number of elements on the stack.
unsigned int _size; ///< Current number of elements that fits on the stack.
} stack_t;
44 changes: 44 additions & 0 deletions src/types/stack.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include <stdlib.h>

#include "stack.h"
#include "types/err.h"

void
stack_init(stack_t* stack)
{
stack->length = 0;

stack->values = malloc(sizeof(void*) * STACK_INITIAL_LENGTH);
stack->_size = STACK_INITIAL_LENGTH;
}

unsigned int
stack_push(stack_t* stack, void* value)
{
if (stack->length >= stack->_size) {
stack->_size += STACK_LENGTH_INCREMENT;
stack->values = realloc(stack->values, sizeof(void*) * stack->_size);
}

stack->values[stack->length] = value;

return stack->length++;
}

error_code_t
stack_pop(stack_t* stack, void** value)
{
if (stack_isempty(stack)) {
return ERR_EMPTY;
}

*value = stack->values[--stack->length];

return ERR_OK;
}

bool
stack_isempty(stack_t* stack)
{
return stack->length == 0;
}

0 comments on commit 9fe6933

Please sign in to comment.