Handout 3.3 - Queues
Handout 3.3 - Queues
In C, a queue is a data structure that follows the FIFO (First In, First Out) principle, meaning
that elements are added to the rear (tail) of the queue and removed from the front (head). You can
implement a queue in C using arrays or linked lists.
Here's a simple queue implementation using both approaches:
#define MAX 5
1
// Remove elements from the queue
int dequeue(Queue* q) {
int item;
if (isEmpty(q)) {
printf("Queue is empty\n");
return -1;
} else {
item = q->items[q->front];
q->front++;
if (q->front > q->rear) {
q->front = q->rear = -1;
}
return item;
}
}
int main() {
Queue* q = createQueue();
enqueue(q, 10);
enqueue(q, 20);
enqueue(q, 30);
enqueue(q, 40);
enqueue(q, 50);
display(q);
dequeue(q);
dequeue(q);
display(q);
return 0;
}
Output:
Inserted 10
Inserted 20
Inserted 30
Inserted 40
Inserted 50
2
Queue contains: 10 20 30 40 50
Queue contains: 30 40 50
typedef struct {
Node* front;
Node* rear;
} Queue;
if (q->front == NULL) {
q->rear = NULL;
}
free(temp);
return item;
}
3
// Display elements of the queue
void display(Queue* q) {
if (q->front == NULL) {
printf("Queue is empty\n");
return;
}
Node* temp = q->front;
printf("Queue contains: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Queue* q = createQueue();
enqueue(q, 10);
enqueue(q, 20);
enqueue(q, 30);
display(q);
dequeue(q);
dequeue(q);
display(q);
return 0;
}
Output:
Inserted 10
Inserted 20
Inserted 30
Queue contains: 10 20 30
Queue contains: 30
Key Operations:
Enqueue: Adds an element to the end of the queue.
Dequeue: Removes an element from the front of the queue.
IsFull (for array implementation): Checks if the queue is full.
IsEmpty: Checks if the queue is empty.
Differences Between Array and Linked List Implementation:
Array: Fixed size, but access is faster (constant time).
Linked List: Dynamic size, but requires additional memory for pointers.
4
Both implementations have their own advantages based on the application’s requirements (e.g.,
memory constraints, dynamic sizing).