Write a program that uses an array to implement a queue.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#include <stdlib.h>
#define MAX 100 /* maximum size of queue */

int *q; /* queue will contain integers */
int N, head, tail;

void queueInit(int max) {
    q = malloc(max+1*sizeof(int));  /* array needs 1 more space than queue size */
    N = max+1;
    head = tail = 0;
}

int queueEmpty() {
    return head == tail;
}

int queueFull() {
    return head == (tail + 1) % N;
}

void enqueue(int item){
    q[tail++] = item;
    tail = tail % N;
}

int dequeue(void) {
    int tmp = head;
    head  = (head + 1) % N;
    return q[tmp];
}

void queueDisplay(void) {
    int i;
    int h = head;
    for (i = h; i != tail; i = h) {
        printf("%d ", q[i]);
        h = (h + 1) % N;
    }
    printf("\n");
}

int main(int argc, char ** argv) {
    int i;
    queueInit(MAX);
    /* add 20 random numbers to queue */
    for (i = 0; i < 20; i++) {
        if (!queueFull())
            enqueue(rand() % 1000);
    }
    printf("Initial Contents: ");
    queueDisplay();
    /* dequeue 10 items from head of queue */
    for (i = 0; i < 10; i++) {
        if (!queueEmpty())
            dequeue();
    }
    printf("Contents after dequeuing 10 items: ");
    queueDisplay();

    free(q);
    return 0;
}

When you compile and execute the above program it produces the following result on Linux:

Initial Contents: 383 886 777 915 793 335 386 492 649 421 362 27 690 59 763 926 540 426 172 736 
Contents after dequeuing 10 items: 362 27 690 59 763 926 540 426 172 736 

Brief Explanation

  • A queue is a first-in first-out (FIFO) data structure.
  • The program starts by initializing a queue to a maximum size of 100.
  • The program iteratively add 20 random numbers to the queue using the function enqueue.
  • The function queueDisplay is used to display the items in the queue.
  • The program then iteratively delete 10 items from the head of the queue using the function dequeue.
  • The statement free(q), frees up the space that was dynamically allocated to the array.

Add comment


Security code
Refresh