Imagine you have tasks arriving in order and you want to process them in the same order they came. Why is a queue better than a stack for this?
Think about the order tasks should be handled when they come in.
Queues follow first-in, first-out (FIFO) order, so tasks are handled in the order they arrive. Stacks follow last-in, first-out (LIFO), so the newest task is handled first, which is not good for scheduling.
What is the printed state of the queue after these operations?
enqueue(10) enqueue(20) dequeue() enqueue(30) dequeue() enqueue(40) print_queue()
Track each enqueue and dequeue step carefully.
After enqueue 10 and 20, queue is 10->20. Dequeue removes 10, queue is 20. Enqueue 30, queue is 20->30. Dequeue removes 20, queue is 30. Enqueue 40, queue is 30->40.
What error will this C code cause when running?
typedef struct Queue {
int items[5];
int front, rear;
} Queue;
void enqueue(Queue* q, int value) {
if (q->rear == 5) {
printf("Queue full\n");
return;
}
q->items[q->rear++] = value;
}
int dequeue(Queue* q) {
if (q->front == q->rear) {
printf("Queue empty\n");
return -1;
}
return q->items[q->front++];
}
int main() {
Queue q = {{0}, 0, 0};
enqueue(&q, 1);
enqueue(&q, 2);
dequeue(&q);
enqueue(&q, 3);
enqueue(&q, 4);
enqueue(&q, 5);
enqueue(&q, 6);
enqueue(&q, 7);
return 0;
}Think about what happens to rear and front indexes after dequeues and enqueues.
The linear queue implementation checks full condition only with rear == 5, without accounting for space freed by dequeues (front advancement). After the sequence: enqueue 1,2; dequeue (front=1, rear=2); enqueue 3,4,5 (rear=5); then enqueue 6 and 7 print "Queue full" twice and stop adding, even though space was available due to the dequeue.
Given this BFS traversal code snippet on a graph, what is the order of nodes visited?
Queue q;
init_queue(&q);
visited[0] = true;
enqueue(&q, 0);
while (!is_empty(&q)) {
int node = dequeue(&q);
printf("%d ", node);
for each neighbor in graph[node] {
if (!visited[neighbor]) {
visited[neighbor] = true;
enqueue(&q, neighbor);
}
}
}Graph edges: 0->1, 0->2, 1->3, 2->3
BFS visits nodes level by level starting from the source.
Start at 0, enqueue neighbors 1 and 2. Dequeue 1, enqueue 3. Dequeue 2, 3 already visited. Dequeue 3. Order: 0 1 2 3.
What problem does a circular queue solve that a simple linear queue does not?
Think about what happens when you dequeue items from a fixed-size array queue.
A simple queue implemented with an array moves front forward on dequeues but rear only moves forward on enqueues. After some dequeues, the front moves ahead leaving unused space at the start. A circular queue wraps around so rear can use that space, avoiding wasted memory and overflow.
