aboutsummaryrefslogtreecommitdiffstats
path: root/src/stack.c
diff options
context:
space:
mode:
authorMaksymilian Jopek <maks@jopek.eu>2023-03-26 15:53:00 +0200
committerMaksymilian Jopek <maks@jopek.eu>2023-03-26 17:37:35 +0200
commit5a2665c21b511ef90967af053f6a1d504b78afff (patch)
tree12b6727b0f1742132063eed1927b98c81f7352b1 /src/stack.c
downloadcstructures-5a2665c21b511ef90967af053f6a1d504b78afff.tar.gz
cstructures-5a2665c21b511ef90967af053f6a1d504b78afff.tar.zst
cstructures-5a2665c21b511ef90967af053f6a1d504b78afff.zip
Stack, queue and graph data structures implemented in C using linked lists.
Diffstat (limited to 'src/stack.c')
-rw-r--r--src/stack.c50
1 files changed, 50 insertions, 0 deletions
diff --git a/src/stack.c b/src/stack.c
new file mode 100644
index 0000000..7c83c87
--- /dev/null
+++ b/src/stack.c
@@ -0,0 +1,50 @@
+#include "stack.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+Stack *stackAlloc() {
+ Stack *new = malloc(sizeof(Stack));
+ new->first = NULL;
+ new->last = NULL;
+ return new;
+}
+
+void stackAdd(Stack *stack, int item) {
+ struct queueItem *new = malloc(sizeof(struct queueItem));
+ new->item = item;
+ if (stack->first) {
+ // printf("stack->first is NOT NULL");
+ new->next = NULL;
+ new->previous = stack->first;
+ stack->first->next = new;
+ stack->first = new;
+ } else {
+ // printf("stack->first is NULL");
+ new->next = NULL;
+ new->previous = NULL;
+ stack->first = new;
+ stack->last = new;
+ }
+}
+
+int stackPop(Stack *stack) {
+ if (!stack->first) {
+ return -1;
+ }
+ int out = stack->first->item;
+ struct queueItem *toFree = stack->first;
+ stack->first = toFree->previous;
+ free(toFree);
+ return out;
+}
+
+void stackFree(Stack *stack) {
+ struct queueItem *s = stack->first;
+ struct queueItem *t = NULL;
+ while (s) {
+ t = s->previous;
+ free(s);
+ s = t;
+ }
+ free(stack);
+}