C Queue

Summary: in this tutorial, you will learn how to implement the C queue data structure using array.

Introduction to queue data structure

Queue is a collection of objects that are added and removed based on the first-in first-out (FIFO) principle. It means that the first element added to the queue will be first one to be removed from the queue.

Don’t be confused a queue with a stack, because a stack works based on the last-in first-out (LIFO) principle.

customers queueA good example of a queue is a line of customers in front of a shop. A new addition to the queue made to the back of the queue, whereas removal from the queue i.e., customer is served happens in the front of the queue. This is called first-come first-served.

There are two main operations in a queue: enqueue and dequeue.

  • Enqueue: inserts an element into the back of the queue.
  • Dequeue: removes an element from the front of the queue.

C queue implementation

We can implement the queue data structure in C using array. We add an element to the back of the queue, whereas we remove an element from the front of the queue. Therefore we need two pointers: head and tail to track the front and the back of the queue.

C Queue

The queue first is empty so we need to initialize the head and tail pointers:

The queue is empty when the head and the tail pointers point to the same position:

Whenever we enqueue an element, we increase the tail pointer 1 position:

When we dequeue an element, we increase the head pointer 1 position until the head pointer reaches the tail pointer i.e., the queue is empty.

The queue is full when the tail and the size of the queue are equal.

The following program demonstrates the queue data structure:

queue.h

queue.c

main.c

The following is the output of the program when we enqueue 1, 2, 3, 4, 5.

You can download the C queue implementation project in the following link.

C Queue (15.7 kB) 474 downloads

In this tutorial, you have learned how to implement queue data structure in C using array.