From 6c33d90aaf83e96f071932080bb81dbdd26c2f3a Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Wed, 25 Sep 2019 21:46:31 -0400 Subject: [PATCH] Add ability to add something to the front of the queue --- queue.c | 25 +++++++++++++++++++++++++ queue.h | 1 + 2 files changed, 26 insertions(+) diff --git a/queue.c b/queue.c index 787dee9..6f07adc 100644 --- a/queue.c +++ b/queue.c @@ -43,6 +43,30 @@ int enqueue(struct queue *q, void *item) { return 0; } +/** + * Enqueue an item in the given queue, but allow it to cut the line and insert it at the front. + * + * @param q + * @param item + * @return int + */ +int priority_enqueue(struct queue *q, void *item) { + if (q->n == q->cap) { + return -1; + } + + // Shift all of the items back. + for (int i = q->n ; i > 0; i--) { + q->items[i] = q->items[i - 1]; + } + + // Put the new item at the front + q->items[0] = item; + q->n++; + + return 0; +} + /** * Dequeue an item from the given queue. * @@ -57,6 +81,7 @@ int dequeue(struct queue *q, void **item) { q->n--; *item = q->items[0]; + // Shift all of the items forward. for (int i = 1; i <= q->n; i++) { q->items[i-1] = q->items[i]; } diff --git a/queue.h b/queue.h index aab2ce0..63b8848 100644 --- a/queue.h +++ b/queue.h @@ -10,6 +10,7 @@ struct queue { struct queue init_queue(int cap); void free_queue(struct queue *q); int enqueue(struct queue *q, void *item); +int priority_enqueue(struct queue *q, void *item); int dequeue(struct queue *q, void **item); #endif \ No newline at end of file