diff --git a/semester3/exercises/exercise3.21.c b/semester3/exercises/exercise3.21.c new file mode 100644 index 0000000..1652654 --- /dev/null +++ b/semester3/exercises/exercise3.21.c @@ -0,0 +1,105 @@ +#include +#include + +typedef struct doubleStack { + int capacity; + int top1; + int top2; + int *arr; +} doubleStack; + +doubleStack *createStack(int capacity) { + doubleStack *new = malloc(sizeof(doubleStack)); + new->capacity = capacity; + new->top1 = -1; + new->top2 = capacity; + + if (capacity <= 0) { + return NULL; + } + new->arr = malloc(sizeof(int) * capacity); + + return new; +} + +void removeStack(doubleStack *st) { + free(st->arr); + free(st); +} + +void push(doubleStack *st, int in, int side) { + // side == 0: top1 + // side == 1: top2 + if (st->top1 == st->top2 - 1) { + printf("ERR: array is full\n"); + return; + } + + if (side == 0) { + st->top1++; + st->arr[st->top1] = in; + } else { + st->top2--; + st->arr[st->top2] = in; + } +} + +int top(doubleStack *st, int side) { + if (side == 0) { + return st->arr[st->top1]; + } else { + return st->arr[st->top2]; + } +} + +int isEmpty(doubleStack *st, int side) { + if (side == 0) { + return (st->top1 == -1); + } else { + return (st->top2 == st->capacity); + } +} + +void pop(doubleStack *st, int side) { + if (!isEmpty(st, side)) { + if (side == 0) { + st->top1--; + } else { + st->top2--; + } + } else { + printf("ERR: array is empty\n"); + } +} + +int main(void) { + doubleStack* test = createStack(5); + + push(test, 1, 0); + printf("Top of left stack is %d\n", top(test, 0)); + push(test, 2, 0); + printf("Top of left stack is %d\n", top(test, 0)); + push(test, 3, 0); + printf("Top of left stack is %d\n", top(test, 0)); + push(test, 4, 0); + printf("Top of left stack is %d\n", top(test, 0)); + push(test, 5, 0); + printf("Top of left stack is %d\n", top(test, 0)); + push(test, 6, 0); + printf("Top of left stack is %d\n", top(test, 0)); + pop(test, 0); + push(test, 6, 0); + printf("Top of left stack is %d\n", top(test, 0)); + + pop(test, 0); + pop(test, 0); + + push(test, 9, 1); + printf("Top of right stack is %d\n", top(test, 1)); + push(test, 8, 1); + printf("Top of right stack is %d\n", top(test, 1)); + + removeStack(test); + + return 0; +}