Skip to content

Instantly share code, notes, and snippets.

@ardrabczyk
Created September 1, 2015 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ardrabczyk/57a7e3cb9b53392e4cea to your computer and use it in GitHub Desktop.
Save ardrabczyk/57a7e3cb9b53392e4cea to your computer and use it in GitHub Desktop.
C stack implementation
#include <stdio.h>
#include <stdlib.h>
#define _E(msg, args...) \
do{ \
printf( "[ERROR][%s][%d]: ", __FUNCTION__, __LINE__); \
printf( (msg), ##args); \
}while(0)
struct stack
{
char *data;
int max_size;
int top;
};
int stack_init(struct stack *stack, size_t size)
{
if (size == 0)
{
_E("Size cannot be zero\n");
return 1;
}
char *new_data = malloc(sizeof(char) * size);
if (new_data == NULL)
{
_E("Failed to allocate buffer for a new"
" stack\n");
return 2;
}
stack->data = new_data;
stack->max_size = size;
stack->top = -1;
return 0;
}
void stack_deinit(struct stack *stack)
{
free(stack->data);
}
int stack_push(struct stack *stack, char val)
{
if (stack->top == stack->max_size - 1)
{
_E("Stack is full\n");
return 1;
}
stack->data[++(stack->top)] = val;
return 0;
}
int stack_pop(struct stack *stack)
{
if (stack->top == -1)
{
_E("Stack is empty\n");
return 1;
}
--stack->top;
return 0;
}
int stack_is_empty(struct stack *stack)
{
int ret = stack->top == -1 ? 1 : 0;
return ret;
}
char stack_get_top_value(struct stack *stack)
{
if (stack_is_empty(stack))
{
_E("Stack is empty\n");
return 1;
}
return stack->data[stack->top];
}
int main(void)
{
struct stack my_stack;
if (stack_init(&my_stack, 2))
{
fprintf(stderr, "stack_init() failed. Exiting\n");
exit(EXIT_FAILURE);
}
printf("Stack size: %d\n", my_stack.max_size);
printf("Is stack empty: %s\n", stack_is_empty(&my_stack) ? "yes" :
"no");
puts("Push 100");
stack_push(&my_stack, 100);
printf("Is stack empty: %s\n", stack_is_empty(&my_stack) ? "yes" :
"no");
printf("Stack top: %d\n", stack_get_top_value(&my_stack));
puts("Push 101");
stack_push(&my_stack, 101);
printf("Stack top: %d\n", stack_get_top_value(&my_stack));
puts("Push 102");
stack_push(&my_stack, 102);
puts("Remove element");
stack_pop(&my_stack);
printf("Stack top: %d\n", stack_get_top_value(&my_stack));
puts("Push 103");
stack_push(&my_stack, 103);
printf("Stack top: %d\n", stack_get_top_value(&my_stack));
stack_deinit(&my_stack);
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment