Skip to content

Instantly share code, notes, and snippets.

@tusqasi
Created December 22, 2022 12:57
Show Gist options
  • Save tusqasi/b06aa2888b37adcecd13de48beeb1f5d to your computer and use it in GitHub Desktop.
Save tusqasi/b06aa2888b37adcecd13de48beeb1f5d to your computer and use it in GitHub Desktop.
Just implementing stacks
#include <stdio.h>
#include <stdlib.h>
// array based stack
// stack has a size
// it has a end element pointer. That is pretty much it
typedef enum { F, T } boolean;
typedef struct stack {
int *elements;
int size;
int end;
} Stack;
Stack *make_stack(int size) {
Stack *new_stack = (Stack *)malloc(1 * sizeof(Stack));
new_stack->size = size;
new_stack->elements = (int *)malloc(sizeof(int) * size);
new_stack->end = 0;
return new_stack;
}
boolean is_empty(Stack *s) { return (s->end == 0); }
boolean push_to_stack(int element, Stack *stack) {
if (stack->end >= stack->size && stack->end != 0) {
fprintf(stderr, "Stack full\n");
return 0;
}
stack->elements[stack->end] = element;
stack->end++;
return 1;
}
boolean pop_stack(Stack *stack) {
if (stack->end <= 0) {
fprintf(stderr, "Stack empty\n");
return 0;
}
stack->elements[stack->end] = 0;
stack->end--;
return 1;
}
int peek_stack(Stack *s) { return s->elements[s->end]; }
int main() {
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment