Simvik

Small priority queue

Keep pending jobs ordered by priority in a fixed array. A medium embedded C problem (Buffers and data structures), run and graded in the browser.

medium · Buffers and data structures · queue · scheduling

A cooperative scheduler picks the highest-priority pending job. A zero-initialised pq_t is empty.

  • pq_push adds a job and returns true, or returns false when the queue is full.
  • pq_pop removes the job with the highest prio into *id and returns true, or returns false when the queue is empty. Among jobs of equal priority, the one pushed first comes out first.

Starter code

bool pq_push(pq_t *q, uint8_t prio, uint8_t id) {
  return false;
}

bool pq_pop(pq_t *q, uint8_t *id) {
  return false;
}

Example tests

Highest priority first

pq_t q = { 0 };
pq_push(&q, 1, 10); pq_push(&q, 3, 30); pq_push(&q, 2, 20);
uint8_t id;
while (pq_pop(&q, &id)) printf("%u ", id);
printf("\n");

Expected output:

30 20 10

Empty queue

pq_t q = { 0 };
uint8_t id = 5;
printf("%d %u\n", pq_pop(&q, &id), id);

Expected output:

0 5

Learn it first

More Buffers and data structures problems