add stack and separate queue and stack tests in main

This commit is contained in:
jacekpoz 2024-03-10 14:19:56 +01:00
parent 13bcfc37f6
commit 34c236ad86
Signed by: poz
SSH key fingerprint: SHA256:JyLeVWE4bF3tDnFeUpUaJsPsNlJyBldDGV/dIKSLyN8
4 changed files with 112 additions and 5 deletions

View file

@ -12,7 +12,7 @@ NAME = zad1
SRC = src
BIN = target
_PROG = main.c queue.c
_PROG = main.c queue.c stack.c
PROG = $(addprefix $(SRC)/, $(_PROG))
OBJ = $(_PROG:.c=.o)

View file

@ -0,0 +1,17 @@
#ifndef _KIK_ZAD1_STACK_H
#define _KIK_ZAD1_STACK_H
#include <stdbool.h>
#include <stddef.h>
typedef struct Stack Stack;
Stack *stack_new(size_t size, size_t element_size);
void stack_free(Stack *stack);
void *stack_pop(Stack *stack);
bool stack_push(Stack *stack, void *value);
#endif // _KIK_ZAD1_STACK_H

View file

@ -1,13 +1,12 @@
#include <queue.h>
#include <stack.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
srand((unsigned int)time(NULL));
Queue *q = queue_new(50, sizeof(long));
void test_queue(size_t size) {
Queue *q = queue_new(size, sizeof(long));
for (size_t i = 0; i < 50; ++i) {
long val = rand() % 1000;
@ -32,6 +31,44 @@ int main(void) {
}
queue_free(q);
}
void test_stack(size_t size) {
Stack *s = stack_new(size, sizeof(long));
for (size_t i = 0; i < 50; ++i) {
long val = rand() % 1000;
printf("%zu: pushing %ld on top of stack...\n", i, val);
if (stack_push(s, &val)) {
printf("%zu: successfully pushed %ld on top of stack!\n", i, val);
} else {
printf("%zu: failed pushing %ld on top of stack :-(\n", i, val);
}
}
for (size_t i = 0; i < 50; ++i) {
void *val_ptr = stack_pop(s);
if (val_ptr == NULL) {
printf("%zu: stack is empty!\n", i);
break;
}
long val = *(long*)val_ptr;
printf("%zu: popped %ld from stack\n", i, val);
free(val_ptr);
}
stack_free(s);
}
int main(void) {
srand((unsigned int)time(NULL));
test_queue(50);
printf("\n\n\n\n\n");
test_stack(50);
return 0;
}

53
lab01/zad1/src/stack.c Normal file
View file

@ -0,0 +1,53 @@
#include <stack.h>
#include <stdlib.h>
#include <string.h>
struct Stack {
size_t top;
size_t size;
size_t element_size;
void **data;
};
Stack *stack_new(size_t size, size_t element_size) {
Stack *ret = malloc(sizeof(Stack));
ret->top = 0;
ret->size = size + 1;
ret->element_size = element_size;
ret->data = malloc((size + 1) * sizeof(void*));
return ret;
}
void stack_free(Stack *s) {
for (size_t i = 0; i < s->top; ++i) {
free(s->data[i]);
}
free(s->data);
free(s);
}
void *stack_pop(Stack *s) {
if (s->top == 0) {
return NULL;
}
void* ret = memcpy(malloc(s->element_size), s->data[s->top], s->element_size);
s->data[s->top] = NULL;
s->top -= 1;
return ret;
}
bool stack_push(Stack *s, void *value) {
if ((s->top + 1) == s->size) {
return false;
}
void *local_value = memcpy(malloc(s->element_size), value, s->element_size);
s->data[s->top + 1] = local_value;
s->top += 1;
return true;
}