Last active
July 11, 2020 06:40
-
-
Save r4j0x00/ce93f4a0809e0c819afa9b257a8ba85b to your computer and use it in GitHub Desktop.
Dynamic stack implementation in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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