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;
}
Related
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;
}
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
void insert_by_priority(int);
void delete_by_priority(int);
void create();
void check(int);
void display_pqueue();
int pri_que[MAX];
int front, rear;
void priority()
{
int n, ch;
char v[20];
printf("\n1 - Insert");
printf("\n2 - Delete");
printf("\n3 - Display");
printf("\n4 - Exit");
create();
while (1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter age to be inserted : ");
scanf("%d",&n);
printf("\nEnter name:");
scanf("%s",&v);
insert_b
y_priority(n);
printf("%s");
break;
case 2:
printf("\nEnter age to delete : ");
scanf("%d",&n);
delete_by_priority(n);
break;
case 3:
display_pqueue();
break;
case 4:
exit(0);
default:
printf("\nChoice is incorrect, Enter a correct choice");
}
}
}
void create()
{
front = rear = -1;
}
void insert_by_priority(int data)
{
if (rear >= MAX - 1)
{
printf("\nQueue overflow no more elements can be inserted");
return;
}
if ((front == -1) && (rear == -1))
{
front++;
rear++;
pri_que[rear] = data;
return;
}
else
check(data);
rear++;
}
void check(int data)
{
int i,j;
for (i = 0; i <= rear; i++)
{
if (data >= pri_que[i])
{
for (j = rear + 1; j > i; j--)
{
pri_que[j] = pri_que[j - 1];
}
pri_que[i] = data;
return;
}
}
pri_que[i] = data;
}
void delete_by_priority(int data)
{
int i;
if ((front==-1) && (rear==-1))
{
printf("\nQueue is empty no elements to delete");
return;
}
for (i = 0; i <= rear; i++)
{
if (data == pri_que[i])
{
for (; i < rear; i++)
{
pri_que[i] = pri_que[i + 1];
}
pri_que[i] = -99;
rear--;
if (rear == -1)
front = -1;
return;
}
}
printf("\n%d not found in queue to delete", data);
}
void display_pqueue()
{
if ((front == -1) && (rear == -1))
{
printf("\nQueue is empty");
return;
}
for (; front <= rear; front++)
{
printf(" %d ", pri_que[front]);
}
front = 0;
}
I have this code on priority queue but i am unable to insert a string alongside the integer like a sorted record i.e
AGE | NAME
78 | abcd
75 | bcdfe
.............etc
I tried using scanf statements but to no avail it prints it seperately or do i have to use emplace?what will be the code changes? but how to implement using user input?Or do i have to implement another data structure? if yes then how?
I tried to make a binary search tree with recursion. I've only written out the insert and search functionality. However, my search function is faulty. I'm stuck on line 39, where if I do not find the value present in my tree, it doesn't return me the message that the value is not found. Please help!
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int key;
struct node* left;
struct node* right;
}node;
struct node* root= NULL;
int contains(node* temp, int el){
if (el==temp->key) {
return 1;
}
else if(el< temp->key) return contains(temp->left, el);
else return contains(temp->right, el);
}
void searchPrompt(void){
int el=-1;
do{
printf(" Search key or press -1 to return to menu: ");
scanf("%d", &el);
if(el>0){
if (root==NULL) printf("\tError: tree is empty\n");
else {
if(contains(root, el)) printf("\tKey %d is found\n",el);
else printf("\tKey %d is not found\n",el);
}
}
else if (el<-1||el==0) printf("\tError: key not positive\n");
}while (el!=-1);
printf(" <Exit search method>\n\n");
}
//for search
void preOrder(node* temp){
if (temp!=NULL){
printf("%d ",temp->key);
preOrder(temp->left);
preOrder(temp->right);
}
}
//for insertion
void insertNode(node* current, int value){
if(value< current->key){
if (current->left == NULL) {
current->left=(node*) malloc(sizeof(node));
current->left->key = value;
printf("\tSuccess! Value inserted: %d\n", current->left->key);
}
else {
insertNode(current->left, value);
}
}
else {
if (current->right == NULL) {
current->right=(node*) malloc(sizeof(node));
current->right->key = value;
printf("\tSuccess! Value inserted: %d\n", current->right->key);
}
else {
insertNode(current->right, value);
}
}
}//end insert
void insert(int value){
if(root==NULL){ //empty tree
root =(node*) malloc(sizeof(node));
root->key= value;
printf("\tPrint root here: %d\n", value);
root->left= NULL;
root->right=NULL;
printf("\tSuccess! Value inserted: %d\n", root->key);
}
else {
insertNode(root, value);
}
printf("\tResult: ");
preOrder(root);
printf("\n");
}
void insertPrompt(void){
int value=-1;
do{
printf(" Insert value or press -1 to return to menu: ");
scanf("%d", &value);
if(value>0)
insert(value);
else if (value<=0)printf("\tError: key not positive\n");
}while (value!=-1);
printf(" <Exit insert method>\n\n");
}
int menuPrompt(void){
int choice=-1;
do{
printf("Enter <1> Search <2> Insert <3> Delete <4> Print Tree <5> Quit: ");
scanf("%d", &choice);
if(choice>5 || choice<1) printf("Error: invalid input! \n\n");
} while(choice>5 || choice<1);
return choice;
}
int main(int argc, char *argv[]){
int choice=-1;
int value=-1;
while(choice!=5){
choice=menuPrompt();
switch(choice){
case 1:
searchPrompt();
break;
case 2:
insertPrompt();
break;
case 3:
break;
case 4:
break;
case 5:
printf("<Exit program> \n");
break;
}//end switch
}
system("PAUSE");
return 0;
}
int contains(node* temp, int el){
if(temp==NULL) return 0;
if (el==temp->key) {
return 1;
}
else if(el< temp->key) return contains(temp->left, el);
else return contains(temp->right, el);
}
This solved both the problem ..saves you from UB and also from wrong behavior in case elemnt not found.
At BLUEPIXY mentioned set left and right inserted new node to NULL.
why is it needed you might ask ..but the thing is when you don't find
an element eventually you will reach some leaf node. And then you will
go to left or right and if you set it to NULL you will call contain
with NULL as parameter and then it will return 0 as you expect it to
be.
//for insertion
void insertNode(node* current, int value){
if(value< current->key){
if (current->left == NULL) {
current->left=(node*) malloc(sizeof(node));
current->left->key = value;
current->left->left = NULL;
current->left->right = NULL;
printf("\tSuccess! Value inserted: %d\n", current->left->key);
}
else {
insertNode(current->left, value);
}
}
else {
if (current->right == NULL) {
current->right=(node*) malloc(sizeof(node));
current->right->key = value;
current->right->left = NULL;
current->right->right = NULL;
printf("\tSuccess! Value inserted: %d\n", current->right->key);
}
else {
insertNode(current->right, value);
}
}
}//end insert
Is this what I needed to do with the left and right of my new node? #BLUEPIXY #coderredoc
I'm attempting to create a program that would allow the user to create a stack data structure using the push, pop, and peek command. However, I keep running into a segmentation fault whenever I try and use the push command! I have no idea why it's not working, because I made sure to use malloc on the stack structure. The peek and pop command are working (as far as I can tell). Any help??
#include<stdlib.h>
#include<stdio.h>
#include "stack.h"
int mainMenuChoice, pushValue;
void mainMenu() {
printf("\nEnter your option: \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Exit\n");
scanf("%d", &mainMenuChoice);
}
Stack * initializeStack() {
Stack *new_stack;
int capacity = 100;
new_stack = (Stack *)malloc(sizeof(Stack));
new_stack->items = (int *)malloc(sizeof(int)*capacity);
new_stack->size = 0;
return new_stack;
}
void push(Stack *new_stack, int item) {
new_stack->items[new_stack->size++] = item;
}
void pop(Stack *new_stack) {
if(new_stack->size == 0) {
printf("The stack is empty, you can't pop any items!\n");
} else {
new_stack->size--;
}
}
int peek(Stack *new_stack) {
if(new_stack->size == 0) {
printf("The stack is empty.\n");
} else {
return new_stack->items[new_stack->size-1];
}
}
void menuOptions(int option) {
Stack *new_stack = initializeStack();
if(option == 1) {
Stack *new_stack;
printf("Enter an element to push: ");
scanf("%d", &pushValue);
push(new_stack, pushValue);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 2) {
pop(new_stack);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 3) {
peek(new_stack);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 4) {
printf("Exiting...\n");
exit(0);
} else {
printf("Invalid input, please try again!\n");
mainMenu();
menuOptions(mainMenuChoice);
}
}
void program() {
mainMenu();
menuOptions(mainMenuChoice);
}
Also, this is the how I've structured the stack:
typedef struct Stack {
int size;
int *items;
}Stack;
Thank you so much in advance, I appreciate it!
I've simplified things a bit. You were having too many recursive calls and new_stack was being redefined [but not reallocated]. You'll still have more work to do (e.g. peek returns a value, but pop does not)
Here's the code [please pardon the gratuitous style cleanup]:
#include <stdlib.h>
#include <stdio.h>
//#include "stack.h"
typedef struct Stack {
int size;
int *items;
} Stack;
int mainMenuChoice;
int pushValue;
Stack *top_stack;
void
mainMenu()
{
printf("\nEnter your option: \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Exit\n");
scanf("%d", &mainMenuChoice);
}
Stack *
initializeStack()
{
Stack *new_stack;
int capacity = 100;
new_stack = (Stack *) malloc(sizeof(Stack));
new_stack->items = (int *) malloc(sizeof(int) * capacity);
new_stack->size = 0;
return new_stack;
}
void
push(Stack *new_stack, int item)
{
new_stack->items[new_stack->size++] = item;
}
void
pop(Stack *new_stack)
{
if (new_stack->size == 0) {
printf("The stack is empty, you can't pop any items!\n");
}
else {
new_stack->size--;
}
}
int
peek(Stack *new_stack)
{
if (new_stack->size == 0) {
printf("The stack is empty.\n");
return -1;
}
else {
return new_stack->items[new_stack->size - 1];
}
}
void
menuOptions(Stack *new_stack,int option)
{
if (option == 1) {
printf("Enter an element to push: ");
scanf("%d", &pushValue);
push(new_stack, pushValue);
}
else if (option == 2) {
pop(new_stack);
}
else if (option == 3) {
peek(new_stack);
}
else if (option == 4) {
printf("Exiting...\n");
exit(0);
}
else {
printf("Invalid input, please try again!\n");
}
}
int
main()
{
top_stack = initializeStack();
while (1) {
mainMenu();
menuOptions(top_stack,mainMenuChoice);
}
return 0;
}
I have created a program to implement a Circular Queue with insert, delete and display. The insertion is working fine and the deletion too but once I try to enter numbers after deletion, nothing is displayed. Here is my source code:
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
void main()
{
int item, choice, cont = 1;
clrscr();
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
getch();
}
void enqueue(int item)
{
if(front==0 && rear==SIZE-1)
printf("\n Queue OverFlow Occured");
else if(front==-1 && rear==-1)
{
front=rear=0;
queue[rear]=item;
}
else if(rear==SIZE-1 && front!=0)
{
rear=0;
queue[rear]=item;
}
else
{
rear++;
queue[rear]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == -1 && rear == -1)
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = front + 1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("\t %d",queue[i]);
}
}
}
Check this code its working fine.
Few suggestions don't use conio.h [clrscr(), and getch()] these are not standards.
Try the code below it worked for me fine.
CODE
#include<stdio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
int main()
{
int item, choice, cont = 1;
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
printf("");
return 0;
}
void enqueue(int item)
{
if(front==0 && rear==SIZE-1)
printf("\n Queue OverFlow Occured");
else if(front==-1 && rear==-1)
{
front=rear=0;
queue[rear]=item;
}
else if(rear==SIZE-1 && front!=0)
{
rear=0;
queue[rear]=item;
}
else
{
rear++;
queue[rear]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == -1 && rear == -1)
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
if(front == rear)
{
front = -1;
rear = -1;
}
else
{
front = front + 1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("\t %d",queue[i]);
}
}
}
OUTPUT
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 5
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 1
Enter the value of item: 43
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 5 43
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 2
Item dequeued: 5
Do you want to continue (1/0): 1
1.Enqueue into queue.
2.Dequeue from queue.
3.display quesue elements
Enter your choice: 3
The queue elements are:
5 43
Do you want to continue (1/0):
Thats a rather confusing code. Since the idea is for the queue to be circular, trying to determine if the queue is full by checking the position of front and rear can be really tricky, aswell as trying to make decisions based on front being higher than rear etc. You can avoid all that. A third variable keeping track of the length of the queue will make your life a whole lot easier.
Try this implementation instead:
#define SIZE 5
int queue[SIZE];
int read = 0, write = 0, size = 0;
void enqueue(int item)
{
if (size >= SIZE)
{
printf("Queue is full");
return;
}
queue[write] = item;
write = (write + 1) % SIZE;
size++;
}
int dequeue()
{
if (size == 0)
{
printf("Queue is empty");
return 0;
}
read %= SIZE;
size--;
return queue[read++];
}
Here is your Fully Functional updated code. I pasted code on Ideone.com Link is link to code
If you don't understand anything just ask. I tried to explain it using comments. And now it is not having any problem that you were facing .
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int front = -1;
int rear = -1;
int queue[SIZE];
void enqueue(int item);
int dequeue();
void display();
void main()
{
int item, choice, cont = 1;
clrscr();
while(cont == 1)
{
printf("\n1.Enqueue into queue.\n");
printf("\n2.Dequeue from queue.\n");
printf("\n3.display quesue elements\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the value of item: ");
scanf("%d",&item);
enqueue(item);
break;
case 2:
item = dequeue();
if(item != NULL)
{
printf("\nItem dequeued: %d\n",item);
}
break;
case 3:
display();
break;
default:
printf("\nInvalid choice.\n");
break;
}
printf("\nDo you want to continue (1/0): ");
scanf("%d",&cont);
}
getch();
}
void enqueue(int item)
{
int temp = (rear+1)%SIZE; //EDIT HERE
if(temp == front){
printf("\n Queue OverFlow Occured");
return;
}
else if(front==-1 )
{
front=rear=0;
queue[rear]=item;
return;
}
else{
rear = (rear+1)%SIZE; // EDIT HERE
queue[rear%SIZE]=item;
}
}
int dequeue()
{
int item = NULL;
if(front == rear) // modified condition
{
printf("\nQueue is empty. Dequeue not possible.\n");
}
else
{
item = queue[front];
queue[front] = NULL;
front++; // front must be incremented
if(front > rear)
{
front = -1;
rear = -1;
}
}
return(item);
}
void display()
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("%d\t",queue[i]);
}
}
}