Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Queue and circular queue-Array

Uploaded by

riddhijain1003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Queue and circular queue-Array

Uploaded by

riddhijain1003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Queue INSERTION

ENQUEUE

1. Check whether the queue is full.


2. If the queue is full, display the overflow message.
3. If the queue is not full, add the new element to the position
pointed to by the rear pointer.
4. Increment the rear pointer.

int queue[MAX_SIZE];
int front = -1;
int rear = -1;

void enqueue(int element) {


if (rear == MAX_SIZE - 1) {
printf("Queue is full");
return;
}
if (front == -1) {
front = 0;
}
rear++;
queue[rear] = element;
}

DEQUEUE

1. Check whether the queue is empty.


2. If the queue is empty, display the underflow message.
3. If the queue is not empty,
4. Increment the front pointer of the queue.
5. remove the element at the front position.
int dequeue() {
if (front == -1 || front > rear) {
printf("Queue is empty");
return -1;
}
int element = queue[front];
front++;
return element;
}

CIRCULAR QUEUE

ENQUEUE

1. Step 1: Check if the queue is full (Rear + 1 % Maxsize = Front)


2. Step 2: If the queue is full, there will be an Overflow error
3. Step 3: Check if the queue is empty, and set both Front and Rear
to 0
4. Step 4: If Rear = Maxsize - 1 & Front != 0 (rear pointer is at the end
of the queue and front is not at 0th index), then set Rear = 0
5. Step 5: Otherwise, set Rear = (Rear + 1) % Maxsize
6. Step 6: Insert the element into the queue (Queue[Rear] = x)
7. Step 7: Exit

#include <stdio.h>
#define MAX_SIZE 5
int a[MAX_SIZE];
int front = -1;
int rear = -1;
void enqueue(int x)
{
if (front == -1 && rear == -1)
{
front = rear = 0;
}
else if ((rear + 1) % MAX_SIZE == front)
{
printf("queue is full\n");
return;
}
else
rear = (rear + 1) % MAX_SIZE;
a[rear] = x;
}

DEQUEUE

1. Step 1: Check if the queue is empty (Front = -1 & Rear = -1)


2. Step 2: If the queue is empty, Underflow error
3. Step 3: Set Element = Queue[Front]
4. Step 4: If there is only one element in a queue, set both Front and
Rear to -1 (IF Front = Rear, set Front = Rear = -1)
5. Step 5: And if Front = Maxsize -1 set Front = 0
6. Step 6: Otherwise, set Front = Front + 1
7. Step 7: Exit

void dequeue()
{
if (front == -1 && rear == -1)
{
printf("queue is empty \n");
return;
}
else if (front == rear)
{
printf(“%d”,a[front]);
front = rear = -1;
}
Else
printf(“%d”,a[front]);
front = (front + 1) % MAX_SIZE;
}

DISPLAY

void display()
{
int i=front;
if(front==-1 && rear==-1)
{
printf("\n Queue is empty..");
}
else
{
printf("\nElements in a Queue are :");
while(i<=rear)
{
printf("%d,", a[i]);
i=(i+1)%MAX_SIZE;
}
}

You might also like