Add ability to add something to the front of the queue

master
Nick Krichevsky 2019-09-25 21:46:31 -04:00
parent cedaf7305f
commit 6c33d90aaf
2 changed files with 26 additions and 0 deletions

25
queue.c
View File

@ -43,6 +43,30 @@ int enqueue(struct queue *q, void *item) {
return 0; 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. * Dequeue an item from the given queue.
* *
@ -57,6 +81,7 @@ int dequeue(struct queue *q, void **item) {
q->n--; q->n--;
*item = q->items[0]; *item = q->items[0];
// Shift all of the items forward.
for (int i = 1; i <= q->n; i++) { for (int i = 1; i <= q->n; i++) {
q->items[i-1] = q->items[i]; q->items[i-1] = q->items[i];
} }

View File

@ -10,6 +10,7 @@ struct queue {
struct queue init_queue(int cap); struct queue init_queue(int cap);
void free_queue(struct queue *q); void free_queue(struct queue *q);
int enqueue(struct queue *q, void *item); int enqueue(struct queue *q, void *item);
int priority_enqueue(struct queue *q, void *item);
int dequeue(struct queue *q, void **item); int dequeue(struct queue *q, void **item);
#endif #endif