Answer to Question #300170 in C for Alpha

Question #300170

Write a C Program to implement circular queue using dynamic memory allocation. Set the


initial capacity of the queue as 2. The capacity should double whenever the queue is Full.


Through proper output show insertion, deletion and doubling the size of the queue.

1
Expert's answer
2022-02-20T15:38:56-0500
#include <stdio.h>
#include <stdbool.h>

struct queue {
  int *data;
  int front, rear;
  int size;
  int capacity;
};

bool queue_create(struct queue *q, size_t capacity) {
  *q = (struct queue) {
    .data = malloc(sizeof(int) * capacity),
    .front = 0,
    .rear = 0,
    .size = 0,
    .capacity = capacity
  };
  return q->data != NULL;
}

bool queue_is_full() {
  return rear == capacity;
}

bool queue_is_empty() {
  return size == 0;
}

bool queue_push(struct queue *q, int val) {
  if (queue_is_full(q)) {
    return false;
  } else {
    q->data[q->rear] = val;
    q->rear = (q->rear + 1) % q->capacity;
    q->size = (q->size + 1);
    return true;
  }
}

bool queue_pop(struct queue *q, int *ret) {
  if (queue_is_empty(q)) {
    return false;
  } else {
    *ret = q->data[q->front];
    q->front = (q->front + 1) % q->capacity;
    q->size = (q->size - 1);
    return true;
  }
}

void queue_remove(struct queue *q) {
  if (q != NULL) {
    free(q->date);
  }
}

int main() {

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS