how to implement queue in c code example

Example 1: how to initialize a queue in c

#include <stdio.h>

#define MAX_QUEUE_SIZE 100;

typedef struct queue {
    int queue[MAX_QUEUE_SIZE];
    int currSize;
    int head;
    int tail;
} queue;

void initQueue(queue *queue) {
    queue->currSize = 0;
    queue->pos = 0;
    queue->head = 0;
    queue->tail = 0;
}

void enqueue(queue *queue, int e) {
    if (isFull()) printf("Queue is full!");

    queue->queue[queue->tail] = e;
    queue->tail = (queue->tail + 1) % MAX_QUEUE_SIZE;
    q->currSize = q->currSize + 1;
}

int dequeue(queue *queue) {
    if (isEmpty()) printf("Queue is empty!");

    int toDequeue = queue->head;
    queue->head = (queue->head + 1) % MAX_QUEUE_SIZE;
    q->currSize = q->currSize - 1;

    return toDequeue;
}

int isEmpty(queue *queue) {
    return (queue->head == queue->tail);
}

int isFull(queue *queue) {
    return (currSize == MAX_QUEUE_SIZE);
}

int main() {
    /* how do I initialize the queue and enq/deq to test? */
    printf("Hello World!\n");
}

Example 2: queue using c

// Queue implementation in C

#include <stdio.h>
#define SIZE 5

void enQueue(int);
void deQueue();
void display();

int items[SIZE], front = -1, rear = -1;

int main() {
  //deQueue is not possible on empty queue
  deQueue();

  //enQueue 5 elements
  enQueue(1);
  enQueue(2);
  enQueue(3);
  enQueue(4);
  enQueue(5);

  // 6th element can't be added to because the queue is full
  enQueue(6);

  display();

  //deQueue removes element entered first i.e. 1
  deQueue();

  //Now we have just 4 elements
  display();

  return 0;
}

void enQueue(int value) {
  if (rear == SIZE - 1)
    printf("\nQueue is Full!!");
  else {
    if (front == -1)
      front = 0;
    rear++;
    items[rear] = value;
    printf("\nInserted -> %d", value);
  }
}

void deQueue() {
  if (front == -1)
    printf("\nQueue is Empty!!");
  else {
    printf("\nDeleted : %d", items[front]);
    front++;
    if (front > rear)
      front = rear = -1;
  }
}

// Function to print the queue
void display() {
  if (rear == -1)
    printf("\nQueue is Empty!!!");
  else {
    int i;
    printf("\nQueue elements are:\n");
    for (i = front; i <= rear; i++)
      printf("%d  ", items[i]);
  }
  printf("\n");
}

Tags:

Misc Example