From 0e153f547a5251b7b9571ab1a932b1cb2ec1e8c1 Mon Sep 17 00:00:00 2001 From: Valentin Gehrke Date: Sun, 21 Feb 2016 16:15:08 +0100 Subject: [PATCH] EPA: Linked Queue --- linkedqueue.c | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 linkedqueue.c diff --git a/linkedqueue.c b/linkedqueue.c new file mode 100644 index 0000000..80518e7 --- /dev/null +++ b/linkedqueue.c @@ -0,0 +1,84 @@ +#include +#include +#include + +typedef struct node { + int element; + struct node* next; +} Node; + +typedef struct queue { + Node* head; + Node* tail; +} *Queue; + +Queue qCreate() { + Queue q = malloc(sizeof(struct queue)); + q->head = NULL; + q->tail = NULL; + return q; +} + +int qEmpty(Queue q) { + return q->head == NULL; +} + +void qPush(Queue q, int element) { + Node * n = malloc(sizeof(Node)); + n->element = element; + n->next = NULL; + if(qEmpty(q)) { + q->head = q->tail = n; + } else { + q->tail->next = n; + q->tail = n; + } +} + +int qPop(Queue q) { + assert(!qEmpty(q)); + Node* n = q->head; + q->head = n->next; + if(q->head == NULL) { + q->tail == NULL; + } + int element = n->element; + free(n); + return element; +} + +void qClear(Queue q) { + Node* iter = q->head; + Node* tmp; + while(iter != NULL) { + tmp = iter; + iter = iter->next; + free(tmp); + } + q->head = NULL; + q->tail = NULL; +} + +void qFree(Queue q) { + qClear(q); + free(q); +} + +int main( int argc, char *argv[] ) { + Queue q = qCreate(); + for(int i = 0; i < 10; i++) { + qPush(q,i*i); + } + + while(!qEmpty(q)) printf("%d ", qPop(q)); + printf("\n"); + + for(int i = 0; i < 10; i++) qPush(q,i); + for(int i = 0; i < 5; i++) qPop(q); + printf("%d\n", qPop(q)); + qClear(q); + assert(qEmpty(q)); + qFree(q); + + return 0; +}