write a simple Queue structure in C, with addQ and removeQ functions
- User
write a simple Queue structure in C, with addQ and removeQ functions
- Assistant
Here is a simple Queue structure in C using arrays with addQ and removeQ functions:
c#define MAX_QUEUE_SIZE 100 struct Queue { int front, rear; int arr[MAX_QUEUE_SIZE]; }; void addQ(struct Queue* q, int value) { if (q->rear == MAX_QUEUE_SIZE - 1) { printf("Queue overflow!\n"); return; } q->rear++; q->arr[q->rear] = value; if (q->front == -1) { q->front = 0; } } int removeQ(struct Queue* q) { if (q->front == -1 || q->front > q->rear) { printf("Queue underflow!\n"); return -1; } int value = q->arr[q->front]; q->front++; return value; } - User
create a function isEmptyQ
- Assistant
Here is the modified Queue structure in C with the added
isEmptyQfunction:c#define MAX_QUEUE_SIZE 100 struct Queue { int front, rear; int arr[MAX_QUEUE_SIZE]; }; void addQ(struct Queue* q, int value) { if (q->rear == MAX_QUEUE_SIZE - 1) { printf("Queue overflow!\n"); return; } q->rear++; q->arr[q->rear] = value; if (q->front == -1) { q->front = 0; } } int removeQ(struct Queue* q) { if (q->front == -1 || q->front > q->rear) { printf("Queue underflow!\n"); return -1; } int value = q->arr[q->front]; q->front++; return value; } int isEmptyQ(struct Queue* q) { return (q->front == -1 || q->front > q->rear); }The
isEmptyQfunction simply checks if the pointer is pointing to (i.e., the queue is empty) or if it is greater than the pointer (i.e., all elements in the queue have been removed). It returns if either of these conditions is true, otherwise it returns . - User
rewrite the queue so it uses the modulus of max queue size
- Assistant
Sure, here is the modified Queue structure in C that uses modulus of the
MAX_QUEUE_SIZE:c#define MAX_QUEUE_SIZE 100 struct Queue { int front, rear; int arr[MAX_QUEUE_SIZE]; }; void addQ(struct Queue* q, int value) { if ((q->rear + 1) % MAX_QUEUE_SIZE == q->front) { printf("Queue overflow!\n"); return; } q->rear = (q->rear + 1) % MAX_QUEUE_SIZE; q->arr[q->rear] = value; if (q->front == -1) { q->front = 0; } } int removeQ(struct Queue* q) { if (q->front == -1) { printf("Queue underflow!\n"); return -1; } int value = q->arr[q->front]; if (q->front == q->rear) { q->front = -1; q->rear = -1; } else { q->front = (q->front + 1) % MAX_QUEUE_SIZE; } return value; } int isEmptyQ(struct Queue* q) { return (q->front == -1); }