Front and Rear pointers
What you'll learn: How a Queue uses two specific markers to keep track of where data enters and exits the list.
The Problem: One is not enough
In a Stack (LIFO), we only need a top pointer because items are added and removed from the same spot. But a Queue is a "First-In, First-Out" structure. Think of a physical line at a movie theater. People join at the back and leave from the front. If you only tracked the front, you wouldn't know where the next person should stand. If you only tracked the back, you wouldn't know who is next to be served.
To manage this in C, we use two separate integer variables (or pointers) typically named front and rear.
The Roles: Entry and Exit
These two markers divide the labor of managing your data:
- Rear (The Tail): This points to the very last element in the queue. When a new piece of data arrives (called Enqueue), we move the
rearforward and place the data there. It’s like the "End of the Line" sign. - Front (The Head): This points to the first element in the queue. When it is time to remove data (called Dequeue), we take the item at the
frontand then move the pointer forward to the next person in line.
Tracking in Code
In a simple array-based queue, these are often just integers representing array indexes. When the queue is empty, we traditionally initialize both to -1.
#include <stdio.h>
#define SIZE 5
struct Queue {
int items[SIZE];
int front;
int rear;
};
void initialize(struct Queue* q) {
// -1 indicates the queue is currently empty
q->front = -1;
q->rear = -1;
}
int main() {
struct Queue myQueue;
initialize(&myQueue);
// When we add the first item:
// 1. Move front to 0
// 2. Move rear to 0
// 3. Place item at items[rear]
return 0;
}
The "Chase"
Imagine the rear and front as two people running a race. The rear is always in the lead, stretching the line longer as more data is added. The front follows behind, shortening the line as data is processed. If the front ever "catches up" and passes the rear, it means the queue is empty!
Key takeaway
The front pointer handles all deletions (removals), while the rear pointer handles all insertions (additions).