Insert and Delete element on Circular Queue - c

I'm studying about circular queue in data structure . As you can see from the code below, I try to delete a specific data and insert data on Circular queue. However, when I try to run it there's a problem when deleting data and insert a new one. I had no clue about it. I was trying to solve this for many hours but I can't find anything. Any help would be appreciated.
#include <stdio.h>
#define SIZE 3
typedef struct queue{
int val[SIZE]={NULL};
int front;
int rear;
}queue;
void display(struct queue *q);
void enqueue(struct queue *q){
int ins,i=1;
if((q->rear == SIZE-1 && q->front == 0) || (q->rear == q->front-1)){
printf("Queue is full!\n");
}
else if (q->front == -1)
{
printf("Enqueue data : ");
scanf("%d",&ins);
q->front = q->rear = 0;
q->val[q->rear] = ins;
}
else if (q->rear == SIZE-1)
{
printf("Enqueue data : ");
scanf("%d",&ins);
q->rear = 0;
q->val[q->rear] = ins;
}
else
{
printf("Enqueue data : ");
scanf("%d",&ins);
q->rear++;
q->val[q->rear] = ins;
}
display(q);
};
void dequeue(struct queue *q);
int main(){
queue *q= new queue;
q->front = -1;
q->rear = -1;
char select;
flag1:
printf("\n------- Please Select Operations ---------\n");
printf("Press e: Enqueue\n");
printf("Press d: Dequeue\n");
printf("Press x: Exit Program\n");
printf("------------------------------------------\n");
printf("Select Menu : ");
scanf(" %c",&select);
switch(select){
case 'e' : enqueue(q); goto flag1;
case 'd' : dequeue(q); goto flag1;
case 'x' : break;
}
return 0;
}
void dequeue(struct queue *q){
int deq,hold;
if (q->front == -1)
{
printf("Queue is Empty");
}
else
{
printf("Dequeue data : ");
scanf("%d",&deq);
for(int i=0;i<SIZE;i++){
if(deq==q->val[i]){
if(i==q->front){
q->val[q->front]=NULL;
q->front = i;
q->rear=q->rear+1;
if(q->rear=SIZE-1){
q->rear=0;
}
}
else
q->val[q->front]=NULL;
}
}
display(q);
}
};
void display(struct queue *q){
int i;
printf("Queue : |");
for (i= 0; i<SIZE; i++){
if(q->val[i]==NULL){
printf(" |");
}
else
printf("%d|", q->val[i]);
}
};

GIGO!
Your code is overly complex.
Complex code requires complex testing and debugging.
Try the following code:
void enqueue( struct queue *q, int v) {
int r = (q.rear + 1) % SIZE
if(( r == q.front) {
printf( "Queue is full!\n");
} else {
q.val[ q.rear] = v;
q.rear = r;
}
};
int dequeue( struct queue *q) {
if( q.front == q.rear) {
printf( "Queue is Empty");
v = NULL; # or whatever (required as a return value)
} else {
v = q.val[ q.front];
q.front = ( q.front + 1) % SIZE;
}
return v;
};
int main() {
queue *q = new queue;
q->front = q->rear = 0;
...
};
To summarize:
rear is index of the youngest element
front is the index of the oldest element
% (the modulus operator) take care of the index overwrapping.
(front == rear) means empty buffer
((rear +1) % SIZE == front) means full buffer.
Please note that this simple algorithm always leave an unused element in the buffer. This is required to distinguish "full" from "empty".

Circular Queue in Java
public class CircularQueue<T> {
private Object[] arr;
private int front = -1, rear = -1;
public CircularQueue(int initialCapacity) {
this.arr = new Object[initialCapacity];
}
public void add(T val) throws Exception {
if (isEmpty()) {
rear++;
front++;
} else if (isFull()) {
throw new Exception("Queue is full");
}
arr[rear] = val;
rear = (rear + 1) % arr.length;
}
public T delete() throws Exception {
if (isEmpty()) {
throw new Exception("No elements in Queue");
}
T temp = (T) arr[front];
front = (front + 1) % arr.length;
return temp;
}
public boolean isEmpty() {
return (front == -1 && rear == -1);
}
public boolean isFull() {
return (front == rear);
}
#Override
public String toString() {
String ret = "[ ";
int temp = front;
do {
ret += arr[temp] + " ";
temp = (temp + 1) % arr.length;
} while (temp != rear);
ret += "]";
return ret;
}
}

Your code is overly and dumbly complex. I think you don't understand circular-queues well.
Here's my simplified code. You can check it out and learn something.
#include<stdio.h>
#include<stdlib.h>
typedef struct _node {
int size,front,rear,*q;
} node;
node *pu;
void initialize() {
if(pu!=NULL)
free(pu);
pu = (node *)malloc(sizeof(node));
printf("\nEnter the size of the queue :- ");
scanf(" %d",&pu->size);
pu->q = (int *)malloc(sizeof(int) * pu->size +1);
pu->front = pu->rear = 0;
}
int isempty() {
return (pu->front == pu->rear);
}
int isfull() {
return ((pu->rear + 1) % pu->size == pu->front);
}
void enqueue(int x) {
if(isfull())
return;
else {
pu->q[pu->rear=(pu->rear +1) % pu->size] = x;
}
}
int dequeue() {
if(isempty())
return '$';
else {
return pu->q[ pu->front = (pu->front + 1) % pu->size];
}
}
void display() {
if(isempty())
return;
else {
for( int i = pu->front + 1; i != (pu->rear +1)%pu->size ; i = ( i +1) % pu->size)
printf("\n %d",pu->q[i]);
}
}
int main() {
// do something in here with the functions.
return 0;
}

Related

How to remove necessary nodes from a binary tree?

Good evening forum members.
The following is on the agenda:
Read a sequence of coordinates (x, y, z) of spatial points from the file, ordered by distance from the point of origin (develop a separate function for calculating the distance and store this value in the data structure);
To bypass use the bottom option from right to left;
Extract from the tree all nodes whose z coordinate falls within the specified range zmin ..zmax (I decided to take from 7 to 14) and indicate their number;
To completely erase the tree, use the direct (from the root) version of the bypass from left to right;
Print the entire tree using a non-recursive function.
Please help with number 3. It is not possible to implement the deletion algorithm according to a given condition. It either does not work at all, or errors arrive (
Thanks in advance to everyone who responds
CODE:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_LEN 8
#define STACK_INIT_SIZE 20
typedef struct Tree {
int z;
int viddal;
struct Tree* left, * right;
} TREE;
typedef struct Stack {
size_t size, limit;
TREE** data;
} STACK;
int Distance(FILE* ftxt, int* vid, int* z_cord);
int CreateTreeFromFile(void);
TREE* NewNode(FILE* f, int viddal, int z);
void AddNewNode(TREE* pnew);
void PrintTreeNIZ(TREE* proot);
void iterPostorder(TREE* root);
void OutputTreeStructure(const char* title);
void ShowTree(TREE* proot, int level);
void ShowLevels(void);
int TreeHeight(TREE* proot);
void EraseTree(TREE* proot);
void DeleteSomeNodes(void);
int DeleteNode(TREE* pnew_adr);
TREE* root;
int main(){
system("chcp 1251");
if (CreateTreeFromFile() == 0)
return 0;
puts("\n Created tree: ");
PrintTreeNIZ(root);
OutputTreeStructure("of created tree");
DeleteSomeNodes();
OutputTreeStructure("of the new tree");
EraseTree(root);
root = NULL;
puts("\n Tree was deleted from DM\n\n");
return 0;
}
int Distance(FILE* ftxt, int *vid, int* z_cord) {
TREE* pel = (TREE*)malloc(sizeof(TREE));
if (feof(ftxt)) {;
return NULL;
}
else {
int x, y, z;
fscanf(ftxt, "%d%d%d", &x, &y, &z);
*z_cord = z;
*vid = sqrt(x * x + y * y + z * z);
}
}
int CreateTreeFromFile()
{
const char* fname = "Cords_1.txt";
FILE* fvoc = fopen(fname, "r");
if (fvoc == NULL) {
printf("\n\t\tCan`t open file %s...\n", fname);
return 0;
}
TREE* node;
int viddal, z;
Distance(fvoc, &viddal, &z);
while ((node = NewNode(fvoc, viddal, z)) != NULL) {
AddNewNode(node);
Distance(fvoc, &viddal, &z);
}
fclose(fvoc);
return 1;
}
TREE* NewNode(FILE* f, int viddal, int z)
{
TREE* pel;
pel = (TREE*)malloc(sizeof(TREE));
if (feof(f)) {
return NULL;
}
pel->viddal = viddal;
pel->z = z;
pel->left = pel->right = NULL;
return pel;
}
void AddNewNode(TREE* pnew) {
if (root == NULL) {
root = pnew;
return;
}
TREE* prnt = root;
do {
if (pnew->viddal == prnt->viddal) {
free(pnew);
return;
}
if (pnew->viddal < prnt->viddal) {
if (prnt->left == NULL) {
prnt->left = pnew;
return;
}
else
prnt = prnt->left;
}
else {
if (prnt->right == NULL) {
prnt->right = pnew;
return;
}
else
prnt = prnt->right;
}
} while (1);
}
void PrintTreeNIZ(TREE* proot)
{
if (proot == NULL)
return;
printf("\n Right Tree");
iterPostorder(proot->right);
printf("\n\n Left Tree");
iterPostorder(proot->left);
printf("\n\n Korin - %d", proot->viddal);
}
void OutputTreeStructure(const char* title)
{
printf("\n\n\n Structur%s:\n\n", title);
ShowLevels();
ShowTree(root, 0);
puts("\n");
}
#define TAB 7
void ShowTree(TREE* proot, int level)
{
if (proot == NULL) return;
ShowTree(proot->right, level + 1);
printf("\n%*c%d", level * TAB + 10, ' ', proot->viddal);
ShowTree(proot->left, level + 1);
}
void ShowLevels(void)
{
int lev;
printf(" Level: ");
for (lev = 1; lev <= TreeHeight(root); lev++)
printf(" %-*d", 6, lev);
printf("\n\n");
}
int TreeHeight(TREE* proot)
{
int lh, rh;
if (proot == NULL) return 0;
lh = TreeHeight(proot->left);
rh = TreeHeight(proot->right);
return lh > rh ? lh + 1 : rh + 1;
}
void EraseTree(TREE* proot)
{
if (proot == NULL)
return;
EraseTree(proot->left);
EraseTree(proot->right);
free(proot);
}
STACK* createStack() {
Stack* tmp = (Stack*)malloc(sizeof(Stack));
tmp->limit = STACK_INIT_SIZE;
tmp->size = 0;
tmp->data = (TREE**)malloc(tmp->limit * sizeof(TREE*));
return tmp;
}
void freeStack(Stack** s) {
free((*s)->data);
free(*s);
*s = NULL;
}
void push(Stack* s, TREE* item) {
if (s->size >= s->limit) {
s->limit *= 2;
s->data = (TREE**)realloc(s->data, s->limit * sizeof(TREE*));
}
s->data[s->size++] = item;
}
TREE* pop(Stack* s) {
if (s->size == 0) {
exit(7);
}
s->size--;
return s->data[s->size];
}
TREE* peek(Stack* s) {
return s->data[s->size - 1];
}
void iterPostorder(TREE* root) {
Stack* ps = createStack();
TREE* lnp = NULL;
TREE* peekn = NULL;
while (!ps->size == 0 || root != NULL) {
if (root) {
push(ps, root);
root = root->left;
}
else {
peekn = peek(ps);
if (peekn->right && lnp != peekn->right) {
root = peekn->right;
}
else {
pop(ps);
printf("\n\t Visited -> %d", peekn->viddal);
lnp = peekn;
}
}
}
freeStack(&ps);
}
// HELP WITH THAT
//--------------------------------------------------------------------------------------------
void DeleteSomeNodes(void)
{
printf("\n\t Deleting needing nods:\n");
TREE* pfind = (TREE*)malloc(sizeof(TREE));
do {
if (pfind->z >= 7 && pfind->z <= 14) {
DeleteNode(root);
printf(" Number %d was deleted from tree\n", root);
}
} while (1);
puts("\n\n");
}
#define NoSubTree 0
#define LeftSubTree -1
#define RightSubTree 1
#define TwoSubTrees 2
int DeleteNode(TREE* pnew_adr)
{
TREE* proot = root;
int subtr;
if (proot == NULL) return 0;
if (pnew_adr->viddal < proot->viddal)
return DeleteNode(proot->left);
if (pnew_adr->viddal > proot->viddal)
return DeleteNode(proot->right);
if (proot->left == NULL && proot->right == NULL)
subtr = NoSubTree;
else if (proot->left == NULL)
subtr = RightSubTree;
else if (proot->right == NULL)
subtr = LeftSubTree;
else
subtr = TwoSubTrees;
switch (subtr) {
case NoSubTree:
root = NULL; break;
case LeftSubTree:
root = proot->left; break;
case RightSubTree:
root = proot->right; break;
case TwoSubTrees:
TREE* pnew_root = proot->right, * pnew_prnt = proot;
while (pnew_root->left != NULL) {
pnew_prnt = pnew_root;
pnew_root = pnew_root->left;
}
pnew_root->left = proot->left;
if (pnew_root != proot->right) {
pnew_prnt->left = pnew_root->right;
pnew_root->right = proot->right;
}
root = pnew_root;
}
free(proot);
return 1;
}
//--------------------------------------------------------------------------------------------

Why is my Hash Map insert function not working?

I am making a Hash Map with people's names as its key using C language. I am using separate chaining to resolve the collision.
This is my code:
#include<stdio.h>
#include<stdlib.h>
#define MinTableSize 1
#include <stdbool.h>
//Colission resolution Using linked list
struct ListNode;
typedef struct ListNode *Position;
struct HashTbl;
typedef struct HashTbl *HashTable;
typedef unsigned int Index;
Index Hash(const char *Key, int Tablesize)
{
unsigned int HashVal = 0;
while(*Key != '\0')
{
HashVal += *Key++;
}
return HashVal % Tablesize;
}
struct ListNode
{
int Element;
Position Next;
};
typedef Position List;
struct HashTbl
{
int TableSize;
List *TheLists;
};
//Function to find next prime number for the size
bool isPrime(int n)
{
if(n <= 1)
{
return false;
}
if(n <= 3)
{
return true;
}
if(n%2 == 0 || n%3 == 0)
{
return false;
}
for(int i = 5; i*i <= n; i = i + 6)
{
if(n%i == 0 || n%(i + 2) == 0)
{
return false;
}
}
return true;
}
int NextPrime(int N)
{
if(N <= 1)
{
return 2;
}
int prime = N;
bool found = false;
while(!found)
{
prime++;
if(isPrime(prime))
{
found = true;
}
}
return prime;
}
HashTable InitializeTable(int TableSize)
{
HashTable H;
int i;
if(TableSize < MinTableSize)
{
printf("Table size is too small\n");
return NULL;
}
H = malloc(sizeof(struct HashTbl));
if(H == NULL)
{
printf("Out of space\n");
return NULL;
}
H->TableSize = NextPrime(TableSize);
H->TheLists = malloc(sizeof(List) * H->TableSize);
if(H->TheLists == NULL)
{
printf("Out of space\n");
return NULL;
}
for(i = 0; i < H->TableSize; i++)
{
H->TheLists[i] = malloc(sizeof(struct ListNode));
if(H->TheLists[i] == NULL)
{
printf("Out of space\n");
return NULL;
}
else
{
H->TheLists[i]->Next = NULL;
}
}
return H;
}
//funtion to find the value
Position Find(const char *Key, HashTable H)
{
Position P;
List L;
L = H->TheLists[Hash(Key, H->TableSize)];
P = L->Next;
while(P != NULL && P->Element != Key)
{
P = P->Next;
}
return P;
}
void Insert(const char *Key, HashTable H)
{
Position Pos;
Position NewCell;
List L;
Pos = Find(Key, H);
if(Pos == NULL)
{
NewCell = malloc(sizeof(struct ListNode));
if(NewCell == NULL)
{
printf("Out of space\n");
return NULL;
}
else
{
L = H->TheLists[Hash(Key, H->TableSize)];
NewCell->Next;
NewCell->Element = Key;
L->Next = NewCell;
printf("Key inserted\n");
}
}
else
{
printf("Key already exist\n");
}
}
int main()
{
char Name[6][20] = {"Joshua", "Erica", "Elizabeth", "Monica", "Jefferson", "Andrian"};
int Size = sizeof(Name[0])/sizeof(Name[0][0]);
HashTable H = InitializeTable(Size);
Insert(Name[0], H);
Insert(Name[1], H);
Insert(Name[2], H);
Insert(Name[3], H);
}
The putout of this code is:
Key inserted
Key inserted
This means, it only successfully inserted two keys, while the other name has not been inserted. I think there's some error in my Insert() function, but I got no clue. I tried using an online compiler and it compile properly.

Unable to display elements in circular queue

I am learning circular queue and I am facing some error.
While displaying the queue it only shows the first and last element, after deleting an element it gets even worse, now I don't know where exactly I am going wrong if it's while inserting an element or displaying.
Here is my code:
#include<stdio.h>
#include<stdlib.h>
struct Queue{
int rear, front;
unsigned capacity;
int *arr;
};
struct Queue* createQueue(unsigned capacity)
{
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = queue->rear = -1;
queue->capacity = capacity;
queue->arr = (int*)malloc(sizeof(int)*capacity);
return queue;
}
struct Queue* enQueue(struct Queue* queue, int data)
{
if(queue->front == 0 && queue->rear == queue->capacity -1)
{
printf("Queue is full.");
}
else if(queue->front == -1)
{
queue->front = queue->rear = 0;
queue->arr[queue->rear] = data;
}
else if(queue->rear = queue->capacity -1 && queue->front != 0)
{
queue->rear = 0;
queue->arr[queue->rear] = data;
}
else
{
queue->rear++;
queue->arr[queue->rear] = data;
}
return queue;
}
struct Queue* deQueue(struct Queue* queue)
{
if(queue->front == -1)
{
printf("Error: Queue underflow.");
}
else if(queue->front == queue->rear)
{
queue->front = queue->rear = -1;
}
else
{
if(queue->front == queue->capacity -1)
{
queue->front = 0;
}
else
{
queue->front++;
}
}
return queue;
}
void printQueue(struct Queue* queue)
{
if(queue->front == -1)
{
printf("Queue is empty.");
}
if(queue->rear >= queue->front )
{
for(int i = queue->front; i <= queue->rear; i++)
{
printf("%d ", queue->arr[i]);
}
}
else
{
for(int i = queue->front; i< queue->capacity; i++)
{
printf("%d ", queue->arr[i]);
}
for (int i = 0; i < queue->rear; i++)
{
printf("%d ", queue->arr[i]);
}
}
}
int main(){
int num, data;
printf("Enter the size of your queue:");
scanf("%d", &num);
struct Queue* queue = createQueue(num);
printf("Start filling the queue:\n");
for (int i = 0; i < num; i++)
{
printf("\nEnter the element:");
scanf("%d", &data);
enQueue(queue, data);
}
printQueue(queue);
deQueue(queue);
printf("\nAfter deleting one element:\n");
printQueue(queue);
printf("\nEnter one element:");
scanf("%d", &data);
enQueue(queue, data);
printf("The final queue is:\n");
printQueue(queue);
return 0;
}
Here is the output:
Enter the size of your queue:5
Start filling the queue:
Enter the element:1
Enter the element:2
Enter the element:3
Enter the element:4
Enter the element:5
1 5 <- this is the queue I am getting
After deleting one element:
5 <- just a 5?
Enter one element:4 <- I entered 4.
The final queue is:
5 -1007484592 565 1734960750 <- why?

Enqueue function of queue using linked list in c

I'm having a problem when using linked list to build a queue program. Here's the full code.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define ERROR_VALUE -300000
typedef struct LinkedNode {
int data;
struct LinkdedNode* link;
}Node;
Node* front;
Node* rear;
void init_queue() { front = rear = NULL; }
int is_empty() { return (front = NULL && rear == NULL); }
int size() {
Node* p;
int count = 0;
if (is_empty())
return 0;
for (p = front; p != rear; p = p->link) {
count++;
return count + 1;
}
}
void enqueue(int e) {
Node* p = (Node*)malloc(sizeof(Node));
p->data = e;
p->link = NULL;
if (is_empty())
front = rear = p;
else {
rear->link = p;
rear = p;
}
}
int dequeue() {
Node* p = front;
int e;
if (is_empty()) {
printf("Queue Empty Error!\n");
return ERROR_VALUE;
}
else if (size() == 1) {
front = rear = NULL;
}
else
front = p->link;
e = p->data;
free(p);
return e;
}
int peek() {
if (is_empty()) {
printf("Queue Empty Error!\n");
return ERROR_VALUE;
}
return front->data;
}
void print_queue() {
Node* p;
printf("QUEUE STATUS: size=%d\n", size());
if (is_empty())
return;
for (p = front; p != NULL; p = p->link)
printf("[%2d] ", p->data);
printf("\n");
}
int main(void) {
int val, sel;
init_queue();
while (1) {
do {
printf("1.ENQUEUE 2.DEQUEUE 3.PEEK 4.STATUS 0.EXIT :");
scanf("%d", &sel);
} while (sel < 0 || sel > 4);
if (sel == 1) {
printf("1.ENQUEUE VALUE ? ");
scanf("%d", &val);
enqueue(val);
}
else if (sel == 2) {
val = dequeue();
if (val != ERROR_VALUE)
printf("2.DEQUEUE VALUE = %d\n", val);
}
else if (sel == 3) {
val = peek();
if (val != ERROR_VALUE)
printf("3.PEEK VALUE = %d\n", val);
}
else if (sel == 4)
print_queue();
else if (sel == 0) break;
}
return 0;
}
I didn't made is_full() function because linked list is "dynamic". When debugging, the program stops when I try enqueuing value. My guess is that there is something wrong in enqueue function, but cannot find what.
This is wrong:
int is_empty() { return (front = NULL && rear == NULL); }
Note the front = NULL. That means every time you call is_empty(), front gets set to NULL, which then causes is_empty() to return 0 because front = NULL evaluates to NULL.
You need to change is_empty() to
int is_empty() { return (front == NULL && rear == NULL); }
And this is exactly why many programmers use "Yoda conditions" like NULL == front - they prevent this type of bug because if you write = instead of == the code will fail to compile.
And, as you've noticed, such bugs are very hard to spot in your own code.

Circular Queue Operations Using Array

Code shows basic operations on Circular Queue.
#define maxsize 10
typedef struct queue
{
int data[maxsize];
int f,r;
}myQueue;
myQueue q;
void init(myQueue *q);
int full(myQueue *q);
int empty(myQueue *q);
void enqueue(myQueue *q,int num);
void dequeue(myQueue *q);
void print(myQueue *q);
void main()
{
init(&q);
int op;
do
{
printf("\nCircular queue operations: Press:\n");
printf("1 for enqueue\n");
printf("2 for dequeue\n");
printf("3 to print Circular Queue\n");
int num,choice;
printf("\nEnter choice:\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter number to insert :\n");
scanf("%d",&num);
if(full(&q))
{
printf("\nQueue is full\n");
exit(0);
}
enqueue(&q,num);
break;
case 2: if(empty(&q))
{
printf("\nQueue is empty\n");
exit(0);
}
dequeue(&q);
break;
case 3: printf("Printing current queue: \n");
print(&q);
break;
default:break;
}
printf("Press 1 to continue or 0 to exit:\n");
scanf("%d",&op);
}
while(op);
}
void init(myQueue *q)
{
q->f=-1;
q->r=-1;
}
int full(myQueue *q)
{
if((q->r+1)%maxsize==q->f)
{
return 1;
}
else
return 0;
}
int empty(myQueue *q)
{
if(q->r==-1)
{
return 1;
}
else
return 0;
}
enqueue function is used to add the elements into queue.
void enqueue(myQueue *q,int num)
{
if(empty(&q))
{
q->f=0;
q->r=0;
}
else
{
q->r=(q->r+1)%maxsize;
}
q->data[q->r]=num;
printf("\n%d is enqueued\n",q->data[q->r]);
}
Dequeue function is used to delete elements from the stack.
void dequeue(myQueue *q)
{
int del_num;
del_num=q->data[q->f];
if(q->f==q->r)
{
init(&q);
}
else
{ //To move front to the next position in the circular array.
q->f=(q->f+1)%maxsize;
}
printf("\n%d is dequeued\n",del_num);
}
void print(myQueue *q)
{
int i;
for(i=q->f;i!=q->r;i=(i+1)%maxsize)
{
printf("%d\n",q->data[i]);
}
printf("%d\n",q->data[q->r]);
}
Issue: Circular queue is automatically enqueuing the 0 element in it initially.
However, rest of the operations are working just fine.
I am not able to identify, why it is automatically inserting 0 in the circular queue, without me enqueuing it.
Your print() function always prints q->data[q->r] as its last operation. This makes no sense when your queue is empty. Maybe you can avoid it like this:
void print(myQueue *q)
{
if (empty(q))
return;
int i;
for(i=q->f;i!=q->r;i=(i+1)%maxsize)
{
printf("%d\n",q->data[i]);
}
printf("%d\n",q->data[q->r]);
}
Anyway there are many more problems with your code, which I doubt it is compiling correctly. Just as an example, the function enqueue() receives a parameter of type myQueue*. Then it provides function empty with the address of it, but this is wrong. you have to pass the function the pointer itself, so q instead of &q. The same mistake is repeated over and over again.
1st Code Snippet requiring change:
void enqueue(myQueue *q,int num)
{
The below line is changed.
if(empty(q)==1)
{
q->f=0;
q->r=0;
}
else
{
q->r=(q->r+1)%maxsize;
}
q->data[q->r]=num;
printf("\n%d is enqueued\n",q->data[q->r]);
}
2nd code snippet requiring changed:
void dequeue(myQueue *q)
{
int del_num;
del_num=q->data[q->f];
if(q->f==q->r)
{
Line below is changed.
init(q);
}
else
{ //To move front to the next position in the circular array.
q->f=(q->f+1)%maxsize;
}
printf("\n%d is dequeued\n",del_num);
}
3rd snippet requiring change:
void print(myQueue *q)
{
int i;
Line below is changed.
if(empty(q))
{
printf("Queue empty");
exit(0);
}
else
{
printf("Printing current queue: \n");
for(i=q->f;i!=q->r;i=(i+1)%maxsize)
{
printf("%d\n",q->data[i]);
}
printf("%d\n",q->data[q->r]);
}
}
That makes it perfectly alright. :)
#include <stdio.h>
#define SIZE 5
int items[SIZE];
int front = -1, rear = -1;
int isFull() {
if ((front == rear + 1) || (front == 0 && rear == SIZE - 1)) return 1;
return 0;
}
int isEmpty() {
if (front == -1) return 1;
return 0;
}
void enQueue(int element) {
if (isFull())
printf("\n Queue is full!! \n");
else {
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
printf("\n Inserted -> %d", element);
}
}
int deQueue() {
int element;
if (isEmpty()) {
printf("\n Queue is empty !! \n");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
else {
front = (front + 1) % SIZE;
}
printf("\n Deleted element -> %d \n", element);
return (element);
}
}
void display() {
int i;
if (isEmpty())
printf(" \n Empty Queue\n");
else {
printf("\n Front -> %d ", front);
printf("\n Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE) {
printf("%d ", items[i]);
}
printf("%d ", items[i]);
printf("\n Rear -> %d \n", rear);
}
}
int main() {
deQueue();
enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);
enQueue(6);
display();
deQueue();
display();
enQueue(7);
display();
enQueue(8);
return 0;
}

Resources