Skip to content

Instantly share code, notes, and snippets.

@r4j0x00
Last active July 11, 2020 06:40
Show Gist options
  • Save r4j0x00/ce93f4a0809e0c819afa9b257a8ba85b to your computer and use it in GitHub Desktop.
Save r4j0x00/ce93f4a0809e0c819afa9b257a8ba85b to your computer and use it in GitHub Desktop.
Dynamic stack implementation in C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define stype unsigned long long
struct list {
struct list *prev;
stype val;
};
typedef struct stackStruct {
int size;
struct list* ptr;
} stack;
stack *newStack()
{
stack *s = malloc(sizeof(stack));
s->size = 0;
s->ptr = malloc(sizeof(struct list));
s->ptr->prev = NULL;
return s;
}
void stackPush(stack *s, stype value)
{
s->ptr->val = value;
void* ptr = s->ptr;
s->ptr = malloc(sizeof(struct list));
s->ptr->prev = ptr;
++s->size;
}
stype stackPop(stack *s)
{
if(!s->size)
{
puts("No items in the stack");
abort();
}
stype val = s->ptr->prev->val;
void* ptr = s->ptr->prev;
s->ptr->prev = s->ptr->prev->prev;
free(ptr);
--s->size;
return val;
}
bool stackEmpty(stack *s)
{
return !s->size;
}
stype stackPeep(stack *s)
{
return s->ptr->prev->val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment