diff --git a/bac2/os/chap2/ex5.c b/bac2/os/chap2/ex5.c index 06af55c..f1c2fad 100644 --- a/bac2/os/chap2/ex5.c +++ b/bac2/os/chap2/ex5.c @@ -1,41 +1,44 @@ -#include #include +#include -struct node{ - struct node* prev; +typedef struct Node* LIFO; + +struct Node{ + struct Node* prev; void* data; }; -typedef struct node* LIFO; - -LIFO* mklifo (); -void push(LIFO* lst , void*); -void* pop(LIFO* lst); +LIFO mklifo(); +void push(LIFO*, void*); +void* pop(LIFO*); int main(void) { - char* t = "test"; - LIFO* lifo = mklifo(); - push(lifo, t); - printf("%s", (char *)pop(lifo)); - + int a = 5; + int b = 12; + LIFO lifo = mklifo(); + + push(&lifo, &a); + push(&lifo, &b); + int *c = pop(&lifo); + int *d = pop(&lifo); + + printf("%d\n", *c); + printf("%d\n", *d); } -LIFO *mklifo (){ - LIFO* ret = malloc(sizeof(struct node)); - return ret; +LIFO mklifo(){ + return calloc(1, sizeof(struct Node)); } -void push(LIFO *lst , void *el){ - LIFO* next = mklifo(); +void push(LIFO* lst, void* el){ + LIFO next = mklifo(); (*lst)->data = el; - (*next)->prev = *lst; - lst = next; + next->prev = *lst; + *lst = next; } -void *pop(LIFO *lst){ - void* el; - (*lst)->data = el; +void *pop(LIFO* lst){ *lst = (*lst)->prev; - return el; + return (*lst)->data; } diff --git a/bac2/os/chap2/ex5.o b/bac2/os/chap2/ex5.o index 77ac7fe..025a4bd 100644 Binary files a/bac2/os/chap2/ex5.o and b/bac2/os/chap2/ex5.o differ diff --git a/bac2/os/chap2/ex6.c b/bac2/os/chap2/ex6.c new file mode 100644 index 0000000..d896d87 --- /dev/null +++ b/bac2/os/chap2/ex6.c @@ -0,0 +1,53 @@ +#include +#include + + +typedef struct node{ + void* data; + struct node* next; +} NODE; + +//Could be only head but it allows a complexity of O(1) instead of O(n) for insertion (where n would be the size of the chain) +typedef struct { + NODE* head; + NODE* tail; +} FIFO; + +FIFO mkfifo (); +void enqueue(FIFO *lst ,void* el); +void* dequeue(FIFO *lst); + +int main(void) +{ + int a = 5; + int b = 12; + FIFO fifo = mkfifo(); + + enqueue(&fifo, &a); + enqueue(&fifo, &b); + int *c = dequeue(&fifo); + int *d = dequeue(&fifo); + + printf("%d\n", *c); + printf("%d\n", *d); + +} + +FIFO mkfifo (){ + return (FIFO) {NULL, NULL}; +} + +void enqueue(FIFO *lst ,void *el){ + NODE *new = calloc(1, sizeof(NODE)); + new->data = el; + if(lst->tail != NULL) + lst->tail->next = new; + lst->tail = new; + lst->head = lst->head == NULL ? new : lst->head; +} + +void* dequeue(FIFO *lst){ + void* ret = lst->head->data; + lst->head = lst->head->next; + return ret; +}