Add ability to add something to the front of the queue
parent
cedaf7305f
commit
6c33d90aaf
25
queue.c
25
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];
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue