Created
October 5, 2021 17:28
-
-
Save devil-cyber/68fea57510dd625d9b02854b9631e658 to your computer and use it in GitHub Desktop.
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> | |
#define INT_MIN -999999 | |
struct Queue{ | |
unsigned int capacity; | |
int *arr; | |
int front; | |
int top; | |
int size; | |
}; | |
struct Queue *queue(unsigned int capacity){ | |
struct Queue *q = (struct Queue*)malloc(sizeof(struct Queue)); | |
q->capacity = capacity; | |
q->top = -1; | |
q->front = 0; | |
q->size = 0; | |
q->arr = (int*)malloc(capacity*sizeof(int)); | |
return q; | |
} | |
int isFull(struct Queue *queue){ | |
return queue->size == queue->capacity; | |
} | |
int isEmpty(struct Queue *queue){ | |
return queue->size == 0; | |
} | |
void eneque(struct Queue *queue, int data){ | |
if(isFull(queue)) | |
return; | |
queue->arr[++queue->top % queue->capacity] = data; | |
queue->size += 1; | |
printf("The %d pushed into queue\n",data); | |
} | |
int deque(struct Queue *queue){ | |
if(isEmpty(queue)) | |
return INT_MIN; | |
int data = queue->front; | |
queue[++queue->front % queue->capacity]; | |
queue->size -= 1; | |
return data; | |
} | |
int rear(struct Queue *queue){ | |
if(isEmpty(queue)) | |
return INT_MIN; | |
return queue->arr[queue->top]; | |
} | |
int front(struct Queue *queue){ | |
if(isEmpty(queue)) | |
return INT_MIN; | |
return queue->arr[queue->front]; | |
} | |
int main() | |
{ | |
int capacity = 100; | |
struct Queue *q = queue(100); | |
eneque(q, 10); | |
eneque(q, 20); | |
eneque(q, 30); | |
eneque(q, 40); | |
printf("Front: %d\n",front(q)); | |
printf("Rear: %d\n",rear(q)); | |
deque(q); | |
deque(q); | |
deque(q); | |
printf("Front: %d\n",front(q)); | |
printf("Rear: %d\n",rear(q)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment