how to implement queue using c
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Heya,
In C, a queue can be implemented using:
Queue using an Array
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5 // Define queue size
typedef struct {
int items[SIZE];
int front, rear;
} Queue;
// Initialize queue
void initQueue(Queue *q) {
q->front = -1;
q->rear = -1;
}
// Check if queue is full
int isFull(Queue *q) {
return (q->rear == SIZE - 1);
}
// Check if queue is empty
int isEmpty(Queue *q) {
return (q->front == -1 || q->front > q->rear);
}
// Enqueue operation
void enqueue(Queue *q, int value) {
if (isFull(q)) {
printf("Queue is full!\n");
return;
}
if (q->front == -1) q->front = 0;
q->rear++;
q->items[q->rear] = value;
printf("Inserted: %d\n", value);
}
// Dequeue operation
int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return -1;
}
int item = q->items[q->front];
q->front++;
return item;
}
// Display queue
void display(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return;
}
printf("Queue: ");
for (int i = q->front; i <= q->rear; i++)
printf("%d ", q->items[i]);
printf("\n");
}
// Main function
int main() {
Queue q;
initQueue(&q);
enqueue(&q, 10);
enqueue(&q, 20);
enqueue(&q, 30);
display(&q);
printf("Dequeued: %d\n", dequeue(&q));
display(&q);
return 0;
}
Complexity:
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.