Skip to main content

Circular queue implementation in C

In my previous posts, we have seen what is queue data structure and how to implement it using linked list and array

Is this queue full?
But we have seen that the array implementation had some problem - it would say "Queue is full" even when the queue was not full.










In the image above, there are 3 slots free in the begining of the array. But as back (rear) is equal to size of array -1, the program will say - queue is full.

One way of overcoming this is to implement a circular queue. That is once end of array is reached, go back to beginning of array and insert elements there. Like this.
Image courtesy:maxtudor.com
 As can be seen in this diagram, once we reach end of array, next element 11 is inserted at the beginning of array. Then we continue from there.

We can say that

index = rear % MAX
array[index] = new_element

Similarly when dequeuing, we can say that

index = front % MAX
temp = array[index]

That way, when front and rear exceed MAX, they continue from 0.

Is the queue full or is it empty?

But the problem arises here. How do we determine whether the queue is full? Or the queue is empty?

In case of earlier implementation, rear=front would have meant that queue is empty.

But in the case of circular queue, front = rear may mean queue is empty or it may mean queue is full.

One way of solving this is to use one extra variable, num_ele - number of elements. Enqueue would increment num_ele and dequeue would decrement num_ele. num_ele is 0 - indicates queue is empty. num_ele is MAX indicates queue is full.

Few changes I have made to this implementation are
  1. Store array, rear, front and num_ele in a structure
  2. Initialize rear and front to -1 and initialize num_ele to 0
  3. When enqueing or adding an element
    1. If queue is not full
      1. Increment rear
      2. Add the new element at array[rear%MAX] (Max is size)
  4.  When dequeing or removing an element
    1. If queue is not empty
      1. save array[front%MAX] in temp
      2. Increment front
      3. return temp
  5. To find if the queue is empty
    1. If num_ele is 0 queue is empty
  6. To find if the queue is full
    1. If num_ele = MAX , queue is full
 Let us write code for enqueue now.


    void enqueue(struct queue *qp,int num)
    {
    if(is_full(qp))
    {
    printf("The queue is full. Can not add elements...");
    }
    else
    {
    (qp->rear)++;
    int index = qp->rear % MAX;
    qp->arr[index] = num;

    (qp->num_ele)++;
    if(qp->front==-1)
    qp->front = 0;
    }

    }


    So we increment rear. (qp->rear because we need a pointer to structure queue as we are modifying queue). But if rear exceeds MAX, we need to start from 0. So index = rear%MAX and then we add arr[index] = num.

    But what is the last if statement in the function. You remember that front and rear are initialized with -1. So when first element is added, front should point to that element. That is why front is incremented.

    Next let us write dequeue function.


    int dequeue(struct queue *qp)
    {
    int temp = -1;
    if(is_empty(qp))
    {
    printf("Queue is empty");
    }
    else
    {
    int index = qp->front %MAX;
    temp = qp->arr[index];
    (qp->front)++;
    (qp->num_ele)--;
    }
    return temp;
    }

    Here we are saving arr[front] in temp and then incrementing front. The function returns the value removed from the queue - temp. To take care of wrapping back, we again use % operator. index = front%MAX.

    Next we should write print function which will iterate over all the elements of the queue.


    void print_queue(struct queue *qp)
    {
    int i;
    printf("Queue is ");
    for(i = qp->front;i<=qp->rear;i++)
    printf("%d---",qp->arr[i%MAX]);
    printf("\n");
    }

    We start from front element of array and go till rear element. And as i may be more than size of array, we use i%MAX here too.

    Here is the complete program.


    #include<stdio.h>
    #define MAX 5

    struct queue
    {
    int arr[MAX];
    int front,rear;
    int num_ele;
    };

    void init(struct queue *qp)
    {
    qp->front = qp->rear = -1;
    qp->num_ele = 0;
    }

    int is_empty(struct queue *qp)
    {
    return qp->num_ele==0;
    }

    int is_full(struct queue *qp)
    {
    return qp->num_ele==MAX;
    }

    void enqueue(struct queue *qp,int num)
    {
    if(is_full(qp))
    {
    printf("The queue is full. Can not add elements...");
    }
    else
    {
    (qp->rear)++;
    int index = qp->rear % MAX;
    qp->arr[index] = num;

    (qp->num_ele)++;
    if(qp->front==-1)
    qp->front = 0;
    }
    }

    int dequeue(struct queue *qp)
    {
    int temp = -1;
    if(is_empty(qp))
    {
    printf("Queue is empty");
    }
    else
    {
    int index = qp->front %MAX;
    temp = qp->arr[index];
    (qp->front)++;
    (qp->num_ele)--;
    }
    return temp;
    }

    void print_queue(struct queue *qp)
    {
    int i;
    printf("Queue is ");
    for(i = qp->front;i<=qp->rear;i++)
    printf("%d---",qp->arr[i%MAX]);
    printf("\n");
    }


    int main()
    {
    struct queue q1;
    init(&q1);

    while(1)
    {
    printf("Enter 1 - enqueue 2 - dequeue 3 - exit");
    int opt;
    scanf("%d",&opt);
    if(opt==1)
    {
    int n;
    printf("Enter a number:");
    scanf("%d",&n);
    enqueue(&q1,n);
    print_queue(&q1);

    }
    else if(opt==2)
    {

    int n;
    n = dequeue(&q1);
    if (n!=-1){
    printf("Value dequed is %d\n",n);
    print_queue(&q1);
    }
    }
    else
    break;

    }
    return 0;
    }



    You can download the program from here.

    Comments

    Popular posts from this blog

    Linked list in C++

    A linked list is a versatile data structure. In this structure, values are linked to one another with the help of addresses. I have written in an earlier post about how to create a linked list in C.  C++ has a library - standard template library which has list, stack, queue etc. data structures. But if you were to implement these data structures yourself in C++, how will you implement? If you just use new, delete, cout and cin, and then claim it is your c++ program, you are not conforming to OOPS concept. Remember you have to "keep it together". Keep all the functions and variables together - in a class. You have to have class called linked list in which there are methods - append, delete, display, insert, find, find_last. And there will also be a data - head. Defining node We need a structure for all these nodes. A struct can be used for this purpose, just like C. struct node { int val; struct node * next; }; Next we need to define our class. W

    Swap nodes of a linked list

    Qn: Write a function to swap the adjacent nodes of a singly linked list.i.e. If the list has nodes as 1,2,3,4,5,6,7,8, after swapping, the list should be 2,1,4,3,6,5,8,7 Image from: https://tekmarathon.com Though the question looks simple enough, it is tricky because you don't just swap the pointers. You need to take care of links as well. So let us try to understand how to go about it. Take two adjacent nodes p1 and p2 Let prevnode be previous node of p1 Now link prevnode to p2 Link p2 to p1 Link p1 to next node of p2 So the code will be prevnode -> next = p2; p1 -> next = p2 -> next; p2 -> next = p1; But what about the start node or head? head node does not have previous node If we swap head with second node, modified head should be sent back to caller  To take care of swapping first and second nodes, we can write p1 = head; p2 = head -> next; p1 -> next = p2 -> next; p2 -> next = p1; head = p2;  Now we are read

    Binary tree deletion - non-recursive

    In the previous post we have seen how to delete a node of a binary search tree using recursion. Today we will see how to delete a node of BST using a non-recursive function. Let us revisit the 3 scenarios here Deleting a node with no children just link the parent to NULL Deleting a node with one child link the parent to  non-null child of node to be deleted Deleting a node with both children select the successor of node to be deleted copy successor's value into this node delete the successor In order to start, we need a function to search for a node in binary search tree. Did you know that searching in  a BST is very fast, and is of the order O(logn). To search Start with root Repeat until value is found or node is NULL If the search value is greater than node branch to right If the search value is lesser than node branch to left.  Here is the function NODEPTR find_node (NODEPTR root,NODEPTR * parent, int delval) { NODEPTR nd = root; NODEPTR pa = root; if (root -> v