Last active
February 26, 2022 07:44
-
-
Save Ch-sriram/1daac3cb6d917fcb827a85e060cca5ea to your computer and use it in GitHub Desktop.
Global Circular Queue Implementation in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
static int front = 0; | |
static int rear = 0; | |
static int capacity = 2; | |
static int* q; | |
void enq(int element) { | |
if (((rear+1)%capacity) == front) { // q is full, double the capacity | |
int* newq = (int*)malloc(sizeof(int)*2*capacity); | |
int newrear = 0, newfront = 0, start = (front + 1) % capacity; | |
for (; start != rear; start = (start + 1) % capacity) { // you can write this for loop too, init step is not present | |
newq[++newrear] = q[start]; | |
} | |
newq[++newrear] = q[start]; | |
q = newq; | |
capacity *= 2; | |
front = newfront; | |
rear = newrear; | |
} | |
rear = (rear + 1) % capacity; | |
q[rear] = element; | |
} | |
int deq() { | |
if (front == rear) { // q is empty | |
printf("\nQ is empty"); | |
return -1; | |
} | |
front = (front + 1) % capacity; | |
return q[front]; | |
} | |
int main() { | |
q = (int*)malloc(sizeof(int)*capacity); | |
for (int i = 0; i < 10; ++i) { | |
printf("\nENQ(%d)", i); | |
enq(i); | |
} | |
for (int j = 0; j < 12; ++j) { | |
int dequeuedElement = deq(); | |
if (dequeuedElement != -1) { // q is not empty | |
printf("\n%d is dequeued", dequeuedElement); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment