diff options
| author | Thomas Schmucker <ts@its1.de> | 2020-07-22 17:30:45 +0200 |
|---|---|---|
| committer | Thomas Schmucker <ts@its1.de> | 2020-07-22 17:30:45 +0200 |
| commit | ac55496d881e0a17b3eff85f1faae5aafbc53b50 (patch) | |
| tree | 65b954e994d7bbfc76bc959876e28f7ea9fa708c /queue.c | |
| download | data-structures-ac55496d881e0a17b3eff85f1faae5aafbc53b50.tar.gz data-structures-ac55496d881e0a17b3eff85f1faae5aafbc53b50.tar.bz2 data-structures-ac55496d881e0a17b3eff85f1faae5aafbc53b50.zip | |
erster Commit
Diffstat (limited to 'queue.c')
| -rw-r--r-- | queue.c | 86 |
1 files changed, 86 insertions, 0 deletions
| @@ -0,0 +1,86 @@ | |||
| 1 | /* Standard C */ | ||
| 2 | #include <stdio.h> | ||
| 3 | #include <stdlib.h> | ||
| 4 | #include <stdbool.h> | ||
| 5 | |||
| 6 | /* Project */ | ||
| 7 | #include "util.h" | ||
| 8 | |||
| 9 | typedef int T; | ||
| 10 | |||
| 11 | struct queue_item { | ||
| 12 | struct queue_item *next; | ||
| 13 | T data; | ||
| 14 | }; | ||
| 15 | |||
| 16 | struct queue { | ||
| 17 | struct queue_item *head, *tail; | ||
| 18 | }; | ||
| 19 | |||
| 20 | void | ||
| 21 | queue_init(struct queue *queue) | ||
| 22 | { | ||
| 23 | queue->head = NULL; | ||
| 24 | } | ||
| 25 | |||
| 26 | void | ||
| 27 | queue_put(struct queue *queue, T data) | ||
| 28 | { | ||
| 29 | struct queue_item *new_item; | ||
| 30 | |||
| 31 | if ( (new_item = malloc(sizeof(*new_item))) != NULL ) { | ||
| 32 | struct queue_item *tmp = queue->tail; | ||
| 33 | new_item->data = data; | ||
| 34 | queue->tail = new_item; | ||
| 35 | if ( queue->head == NULL ) | ||
| 36 | queue->head = queue->tail; | ||
| 37 | else | ||
| 38 | tmp->next = queue->tail; | ||
| 39 | } | ||
| 40 | else | ||
| 41 | ERROR("out of memory"); | ||
| 42 | } | ||
| 43 | |||
| 44 | bool | ||
| 45 | queue_get(struct queue *queue, T *data) | ||
| 46 | { | ||
| 47 | if ( queue->head != NULL ) { | ||
| 48 | struct queue_item *next = queue->head->next; | ||
| 49 | *data = queue->head->data; | ||
| 50 | free(queue->head); | ||
| 51 | queue->head = next; | ||
| 52 | |||
| 53 | return true; | ||
| 54 | } | ||
| 55 | else | ||
| 56 | return false; | ||
| 57 | } | ||
| 58 | |||
| 59 | bool | ||
| 60 | queue_empty(struct queue *queue) | ||
| 61 | { | ||
| 62 | return queue->head == NULL; | ||
| 63 | } | ||
| 64 | |||
| 65 | int | ||
| 66 | main() | ||
| 67 | { | ||
| 68 | struct queue queue[1]; | ||
| 69 | |||
| 70 | queue_init(queue); | ||
| 71 | |||
| 72 | for ( int i = 0; i != 10; ++i ) | ||
| 73 | queue_put(queue, i); | ||
| 74 | |||
| 75 | while ( !queue_empty(queue) ) { | ||
| 76 | int i; | ||
| 77 | if ( queue_get(queue, &i) ) | ||
| 78 | printf("%d\n", i); | ||
| 79 | else | ||
| 80 | ERROR("this shouldn't happen!"); | ||
| 81 | } | ||
| 82 | return EXIT_SUCCESS; | ||
| 83 | } | ||
| 84 | |||
| 85 | |||
| 86 | |||
