#include <stdio.h>
#include <limits.h>
#define MAX_SIZE 5
#define FULL INT_MAX
#define EMPTY INT_MIN
int Q[MAX_SIZE]; // linear queue //
int rear = -1;
int front = 0;
// condition for empty is Qsize is zero (front > rear) //
// condition for full is rear is at last index (rear == MAX_SIZE - 1) //
// basic operations on Queue //
int add_Q(int item); // if full returns (INT_MAX) else returns item inserted //
int delete_item_in_Q(); // if empty returns (INT_MIN) else returns deleted item //
size_t Qsize(); // returns 0 if (front > rear) else returns the current size of Q //
// read operations //
int rear_data(); // if empty returns (INT_MIN) else returns rear data //
int front_data(); // if empty returns (INT_MIN) else returns front data //
void read_Q();
void delete_Q();
void get_Q(size_t size);
int main(void){
int size;
printf("\nenter your size(positive) for Queue (less than %d) : ",MAX_SIZE);
scanf("%d",&size);
get_Q(size);
read_Q();
add_Q(66);
read_Q();
delete_item_in_Q();
read_Q();
delete_Q();
read_Q();
return 0;
}
void get_Q(size_t size){
int item;
if(size > MAX_SIZE){
printf("enter valid size \n");
return;
}
for(int i = 0 ; i < size ; i ++){
printf("enter your queue elements : ");
scanf("%d",&item);
add_Q(item);
}
}
int add_Q(int item){
return rear == (MAX_SIZE - 1) ? FULL : (Q[++rear] = item);
}
int delete_item_in_Q(){
return Qsize() ? Q[front++]:EMPTY;
}
size_t Qsize(){
if(front > rear){
front = 0;rear = -1;
}
return (rear - front + 1);
}
int front_data(){
return Qsize() ? Q[front]:EMPTY;
}
int rear_data(){
return Qsize() ? Q[rear]:EMPTY;
}
void read_Q(){
if(!Qsize()){
printf("\nthe queue is empty\n");
return;
}
int i = front;
printf("\nthe queue is : ");
while(1){
printf("%d=>",Q[i++]);
if(i == MAX_SIZE){
printf("\nqueue is full\n");
return;
}
else if (i > rear){
putchar('\n');
return;
}
}
}
void delete_Q(){
while(1){
if(!Qsize()){
printf("\nthe queue is empty\n");
return;
}
printf("the deleted element is : %d\n",Q[front++]);
}
}
In my queue(linear) rear = -1 and front = 0 unlike(front = rear = -1) and assumes user doesn't enter INT_MIN or INT_MAX. I am not checking the return values of many functons like scanf(),add_Q() for simplicity.
rear and front points to valid data if (front <= rear) empty if (front > rear). Qsize() always reinitialize the index back to original in empty state
In order to access queue the above conditions must be "strictly" met or else we say it is empty,
so is this queue a valid one ? my teacher said that it is not a good one (rear or front is pointing at locations inside the array in empty conditions).
Is there any problem in my code ? I have tried to look for errors but none was found (based on my definition).
and I need a better solution that doesn't assume user never enter INT_MIN or INT_MAX (but it should return the added or deleted data).
read_Q() also looks bad. I need a better one for it.