A small C exercise for practicing queues implemented with a singly linked list (FIFO — First In, First Out).
A neighborhood pharmacy serves customers in the order they arrive. Every customer who walks in gets a ticket number and joins the back of the line. The pharmacist always calls the person who has been waiting the longest — the one at the front of the line.
This models a classic queue: new items join at the rear, items leave from the front.
Implement a queue backed by a singly linked list, using two pointers
(front and rear) so that both operations run in O(1):
| Function | Description |
|---|---|
enqueue(Queue *q, int ticketNumber) |
Adds a new ticket at the rear of the line. |
int dequeue(Queue *q) |
Removes and returns the ticket at the front of the line, or -1 if the queue is empty. |
printQueue(const Queue *q) |
Prints the queue from front to rear, e.g. Queue: [1] [2] [3]. |
freeQueue(Queue *q) |
Frees every remaining node in the queue. |
main() already contains a full simulation that exercises all four
functions — it should not be modified. Once the functions above are
implemented correctly, running the program produces the expected output
below.
- Use a singly linked list (
Node -> Node -> ... -> NULL). - Keep both
frontandrearpointers up to date so you never need to walk the whole list to find the last node. enqueuealways inserts at the rear;dequeuealways removes from the front.- Free every node you allocate — no memory leaks.
- Handle the empty-queue case everywhere (
dequeueon an empty queue must not crash, and must return-1).
gcc -Wall -Wextra -std=c11 -o queue main.c
./queue== Pharmacy opens ==
Ticket #1 joins the line.
Ticket #2 joins the line.
Ticket #3 joins the line.
Queue: [1] [2] [3]
Now serving Ticket #1. Come to the counter!
Ticket #4 joins the line.
Queue: [2] [3] [4]
Now serving Ticket #2. Come to the counter!
Now serving Ticket #3. Come to the counter!
Now serving Ticket #4. Come to the counter!
Error: queue is empty, cannot dequeue.
Queue is empty, nobody is waiting.
Error: queue is empty, cannot dequeue.
Trying to serve from an empty queue... nothing happens.
== Pharmacy closes ==
valgrind ./queue