Site Tools


queue

**This is an old revision of the document!**

Table of Contents

Queue

A queue is a first-in, first-out (FIFO) sequence. Elements are added at the back (enqueue) and removed from the front (dequeue). A queue can be implemented over a Linked list with a head and tail pointer, over a Circular buffer for a bounded version, or as a lock-free queue for concurrent use.

// linked-list-backed queue
struct node { int val; struct node *next; };
 
struct queue {
    struct node *head;  // dequeue from here
    struct node *tail;  // enqueue here
};
 
void enqueue(struct queue *q, int val) {
    struct node *n = malloc(sizeof *n);
    n->val = val; n->next = NULL;
    if (q->tail) q->tail->next = n; else q->head = n;
    q->tail = n;
}
 
int dequeue(struct queue *q) {
    struct node *n = q->head;
    int val = n->val;
    q->head = n->next;
    if (!q->head) q->tail = NULL;
    free(n);
    return val;
}

Queues are the natural structure for any processing pipeline where order must be preserved: network packet buffers, OS task schedulers (ready queues), message passing between threads (producer-consumer), and breadth-first search. When both ends need O(1) push and pop, the linked implementation or a circular buffer is preferred over a Dynamic array, where dequeueing from the front would shift all remaining elements.

Operation Time
Enqueue O(1)
Dequeue O(1)
Peek front O(1)
Search O(n)
queue.1781170991.txt.gz · Last modified: by 127.0.0.1