CASE STUDY 02 · DATA STRUCTURES

Advanced Stable priority queue

Hospital Emergency Queue

Translate triage policy into a priority queue that serves more urgent patients first while preserving fair arrival order among equal priorities.

01 · PROBLEM DEFINITION

A normal queue is not clinically sufficient

First-come, first-served is fair only when every waiting case has equal urgency. Emergency departments must allow a later critical patient to be seen before an earlier standard patient. However, patients with equal clinical priority should retain their arrival order.

Educational boundary: This project demonstrates data-structure behaviour. Real clinical triage must use approved medical protocols and trained professionals—not this example priority number.

Register

Create a token and place the patient correctly.

Call next

Remove and free the highest-priority waiting node.

Report

Show service order and counts by category.

02 · TRIAGE POLICY

Define priority before implementation

Numeric priorityLabelOrdering meaning
1CriticalServed before every other category
2EmergencyServed after Critical
3UrgentServed after Emergency
4StandardServed after all urgent categories

Smaller numeric value means higher urgency. Within the same value, smaller arrivalOrder is served first. Therefore the complete key is:

ordering key = (priority ascending, arrivalOrder ascending)

Stability

A priority queue is stable when equal-priority items preserve insertion order. Stability prevents a newly registered Urgent patient from overtaking Urgent patients already waiting.

03 · DATA MODEL

Patient node and queue state

Patient = { token, name, age, priority, arrivalOrder, *next }
Queue state = { *front, nextToken, nextArrival }
MemberRoleInvariant
tokenPublic queue identifierUnique and increasing
priorityUrgency rank1 through 4
arrivalOrderFairness tie-breakerUnique and increasing
nextLinks service orderFinal node points to NULL
frontNext patient to callAlways best ordered node
04 · QUEUE INVARIANTS

Rules that make every dequeue correct

  1. Priorities never decrease while traversing from front.
  2. For equal priorities, arrivalOrder strictly increases.
  3. Every allocated waiting patient is reachable from front exactly once.
  4. front is NULL if and only if the queue is empty.
  5. Calling next removes exactly front and advances to the old front’s next.
Critical
P1, arrival 4
Emergency
P2, arrival 2
Urgent
P3, arrival 1
Urgent
P4, arrival 3
Why the queue can call in O(1): all ordering work is completed during insertion, so the best patient is always at front.
05 · SORTED INSERTION ALGORITHM

Find the first patient who should come later

comesBefore(a,b) compares priority first and arrival order second. Enqueue walks while the new patient does not come before the current node.

  1. Start with position = &front.
  2. While a node exists and the new patient belongs after it, advance to the address of its next link.
  3. Point the new node to the node currently stored at position.
  4. Store the new node at position.
while (*position != NULL && !comesBefore(patient, *position))
    position = &(*position)->next;
patient->next = *position;
*position = patient;

This pointer-to-pointer form handles insertion at front, middle and end without three separate code blocks.

06 · COMPLETE IMPLEMENTATION

Compiler-ready C11 program

programs/hospital-emergency-queue.c
Open Compiler
Loading source…

Design reading guide

Comparator

Understand comesBefore before examining insertion.

Queue mutation

Compare enqueue’s O(n) work with callNext’s O(1).

Lifetime

Registration allocates; service or shutdown frees.

07 · INTERACTIVE TRACING

Trace priority and stability together

  1. A arrives first.
  2. B arrives with higher priority.
  3. B is inserted at front.
  4. C has equal priority to B.
  5. Stable ordering is preserved.
  6. D arrives last but is most urgent.
  7. D moves to front by priority.
  8. The critical patient is served.
  9. Fairness resolves equal priority.
Current state

Press Next to begin.

08 · TEST STRATEGY

Test urgency, fairness and lifetime

Test 1 — Different priorities
Register Standard, Urgent, Critical and Emergency in that order. Display must show Critical, Emergency, Urgent, Standard.
Test 2 — Equal-priority stability
Register A, B and C all as Urgent. They must be called A, then B, then C.
Test 3 — New highest priority
Add Critical to a non-empty lower-priority queue. Critical must become front immediately.
Test 4 — Empty dequeue
Call next on an empty queue. The operation must report empty without dereferencing front.
Test 5 — Validation
Reject blank name, age below 0 or above 130, and priority outside 1–4; free the provisional node.
Test 6 — Complete cleanup
Exit with multiple waiting nodes. Every node must be freed exactly once.
09 · COMPLEXITY & ALTERNATIVES

Where should ordering work happen?

OperationSorted linked queueBinary heapUnsorted list
RegisterO(n)O(log n)O(1)
View/call bestO(1)O(1)/O(log n)O(n)
Display service orderO(n)Requires ordered extractionRequires sorting
Memory localityLowerHighLower

The linked queue is appropriate for teaching and moderate waiting lists because Call Next is simple and display order is already correct. At large scale, a stable heap or four FIFO queues—one per category—would reduce insertion cost.

Four-queue alternative: enqueue into the matching FIFO queue in O(1); dequeue from the first non-empty priority queue. With only four fixed categories, both operations are effectively O(1).
10 · PRACTICE

Check and extend the design

What makes this priority queue stable?

Why is Call Next O(1)?

Extension challenges

  1. Implement four separate FIFO queues and compare complexity.
  2. Add controlled priority reassessment while retaining the original arrival order.
  3. Estimate waiting time from average consultation duration.
  4. Add cancellation by token and test front/middle/tail removal.
  5. Prevent starvation by gradually increasing long-waiting patients’ effective priority.
11 · INTERVIEW PREPARATION

Explain fairness and performance

Why not use a normal FIFO queue?

FIFO cannot allow a critical later arrival to overtake a standard earlier arrival. Clinical urgency is the primary ordering requirement.

How is stable priority maintained?

Comparison uses priority first and monotonically increasing arrivalOrder second, so a new equal-priority patient is inserted after existing peers.

What is starvation?

Low-priority patients may wait indefinitely if higher-priority patients keep arriving. Aging or service quotas can mitigate this.

Why use pointer-to-pointer insertion?

It modifies the exact link that must point to the new node, whether that link is front or a predecessor’s next field.

Would a heap always be better?

No. A heap improves insertion asymptotically but complicates stable ties and ordered display. Choice depends on queue size and operation frequency.

12 · KEY TAKEAWAY

Correct ordering requires an explicit comparator

A priority queue is not merely “sorted by priority”. This system becomes correct only when the ordering key contains both urgency and arrival sequence, validation protects the domain, and allocation ownership covers registration, service and shutdown.