0% found this document useful (0 votes)
19 views

Queue Data Structure Introduction

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

Queue Data Structure Introduction

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

Queue Data Structure (Introduction)

A Queue is another type of Data Structure, generally done via arrays. Generally, Queues
are FIFO i.e. First in First out. A good example would be people standing at a billing counter in a
queue, the person who comes first, will be served first.

More about Queues


 Unlike arrays, where insertion and deletion can happen at any end.
 In Queues, insertion (Enqueue) and deletion (Dequeue) can happen at only one end each.
 Insertion happens at the rear end and deletion happens at the front
 Queues follow FIFO First in First out structure, i.e. the element added first (Enqueued) will
go out of the queue first(Dequeued)
 Unlike stack, which follows, LIFO, last in first out, and stack where both insertion and
deletion happens as one end. For queue insertion(Enqueue) and deletion(Dequeue)
happens at opposite ends.

Queue Operations

 Enqueue: Adding a new item to the Queue Data Structure, in other words, enqueuing new
item to Stack DS.

If the Queue is full, then it is said to be in an overflow condition

 Dequeue: Removing an item from the Queue, i.e. dequeuing an item out.

If a Queue is empty then it is said to be in an underflow condition

 IsEmpty: This returns True If the Queue is empty else returns False
 IsFull: This returns True if the Queue is full else returns false.

Some other notations are Front and Rear, that return the front end read items of the queue.

Representation of Queue
Queue as a data structure can be represented in two ways.

 Stack as an Array (Most popular)


 Stack as a struct (Popular)
 Stack as a Linked List.

1. Enqueue()
 When we require to add an element to the Queue we perform Enqueue() operation.
 Push() operation is synonymous of insertion/addition in a data structure.

2. Dequeue()
 When we require to delete/remove an element to the Queue we perform Dequeue()
operation.
 Dequeue() operation is synonymous of deletion/removal in a data structure.
Applications and uses for Queues
 Heavily used in almost all applications of the operating system, to schedule processes,
moving them in or out of process scheduler.
 FCFS, SJF etc
 Asynchronously i.e. when data resource may be the same but not received at the same
rate.
 Anything that has to do with process and schedule, in the system or code.
#include <bits/stdc++.h>
using namespace std;

// A structure to represent a queue


class Queue {
public:
int front, rear, size;
unsigned capacity;
int* array;
};

// function to create a queue


// of given capacity.
// It initializes size of queue as 0
Queue* createQueue(unsigned capacity)
{
Queue* queue = new Queue();
queue->capacity = capacity;
queue->front = queue->size = 0;

// This is important, see the enqueue


queue->rear = capacity - 1;
queue->array = new int[queue->capacity];
return queue;
}

// Queue is full when size


// becomes equal to the capacity
int isFull(Queue* queue)
{
return (queue->size == queue->capacity);
}

// Queue is empty when size is 0


int isEmpty(Queue* queue)
{
return (queue->size == 0);
}

// Function to add an item to the queue.


// It changes rear and size
void enqueue(Queue* queue, int item)
{
if (isFull(queue))
return;
queue->rear = (queue->rear + 1)
% queue->capacity;
queue->array[queue->rear] = item;
queue->size = queue->size + 1;
cout << item << " enqueued to queue\n";
}

// Function to remove an item from queue.


// It changes front and size
int dequeue(Queue* queue)
{
if (isEmpty(queue))
return INT_MIN;
int item = queue->array[queue->front];
queue->front = (queue->front + 1)
% queue->capacity;
queue->size = queue->size - 1;
return item;
}

// Function to get front of queue


int front(Queue* queue)
{
if (isEmpty(queue))
return INT_MIN;
return queue->array[queue->front];
}

// Function to get rear of queue


int rear(Queue* queue)
{
if (isEmpty(queue))
return INT_MIN;
return queue->array[queue->rear];
}

// Driver code
int main()
{
Queue* queue = createQueue(1000);

enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);
enqueue(queue, 40);

cout << dequeue(queue)


<< " dequeued from queue\n";

cout << "Front item is "


<< front(queue) << endl;
cout << "Rear item is "
<< rear(queue) << endl;

return 0;
}

Output:
10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
40 enqueued to queue
10 dequeued from queue
Front item is 20
Rear item is 40
Queue in C Programming

Basic Information about Queues

Queue is FIFO type i.e. First in First out. In queues inserting an item is called as Enqueue and
removing an item is called as Dequeue.

As given in the image the following about queues is true –

Terminologies
 Enqueue means adding one item to the queue and happens at the rear end of queue
 Dequeue means removal of one item from the queue and happens at the front end of the
queue
 If the max size of queue is reached then the queue is said to be in Overflow condition
 If the queue has no items then queue is said to be in Underflow condition

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>

#define MAX 6

int intArray[MAX];
int front = 0;
int rear = -1;
int itemCount = 0;

int peek() {
return intArray[front];
}
bool isEmpty() {
return itemCount == 0;
}

bool isFull() {
return itemCount == MAX;
}

int size() {
return itemCount;
}

void insert(int data) {

if(!isFull()) {

if(rear == MAX-1) {
rear = -1;
}

intArray[++rear] = data;
itemCount++;
}
}

int removeData() {
int data = intArray[front++];

if(front == MAX) {
front = 0;
}

itemCount--;
return data;
}

int main() {

insert(3);
insert(5);
insert(9);
insert(1);
insert(12);
insert(15);

if(isFull()) {
printf("Queue is full!\n");
}

int num = removeData();

printf("Element removed: %d\n",num);

insert(16);
insert(17);
insert(18);

printf("Element at front: %d\n",peek());

printf("----------------------\n");
printf("index : 5 4 3 2 1 0\n");
printf("----------------------\n");
printf("Queue: ");

while(!isEmpty()) {
int n = removeData();
printf("%d ",n);
}
}

Output:

Queue is full!
Element removed: 3
Element at front: 5
----------------------
index : 5 4 3 2 1 0
----------------------
Queue: 5 9 1 12 15 16

=== Code Execution Successful ===

Queue using Arrays in C (Implementation) | C Program

How Queues work?

You can think of queues as a queue of people at airport ticket counter. The first person to
enter the queue is served by the air hostess at ticket counter first, the last person to enter is
served last. Which is why Queues are called as First in First out (FIFO) system or Last in Last out
system (LILO)

The following are terminologies used in Queue Array implementation –

 Front – The item at the front of the queue is called front item
 Rear – The item at the end of the Queue is called rear item
 Enqueue – Process of adding or inserting a new item in the queue is called as Enqueing
 Dequeueing – Process of removing or deleting an existing item from the queue is called as
dequeueing
 Size – The max size of the queue is called as size an is initialised when the queue is
created
 currSize – The size of queue at any given time is notated as currSize.
C Program to Implement Queues using Arrays

#include
#define SIZE 5

//Basic value initialisation


int queue[SIZE], front = -1, rear = -1;

//Function created to handle enqueue


void enqueue(int item){
if(rear == SIZE-1){
printf("Can't enqueue as the queue is full\n");
}
else{
//The first element condition
if(front == -1){
front = 0;
}

rear = rear + 1;
queue[rear] = item;
printf("We have enqueued %d\n",item);
}
}

//Function created to handle dequeue


void dequeue(){
if(front == -1){
printf("Can't dequeue as the queue is empty\n");
}
else{
printf("We have dequeued : %d\n", queue[front]);
front = front + 1;

//Only happens when the last element was dequeued


if(front > rear){
front = -1;
rear = -1;
}
}
}

//function to print the queue


void printQueue(){
if(rear == -1)
printf("\nUnable to display as queue is empty");
else{
int i;
printf("\nThe queue after enqueue & dequeue ops looks like :");

for(i = front; i <= rear; i++)


printf("%d ",queue[i]);
}
}
int main()
{
//enqueue begins here
enqueue(2);
enqueue(4);
enqueue(6);
enqueue(8);

//dequeue beings here


dequeue();
dequeue();

printQueue();
return 0;
}

Output:

We have enqueued 2
We have enqueued 4
We have enqueued 6
We have enqueued 8
We have dequeued : 2
We have dequeued : 4

The queue after enqueue & dequeue ops looks like :6 8

Problem with simple implementation of Queue using Arrays

The simple implementation of queues faces a unique problem

 Whenever we do simultaneous enqueue or dequeue in the queue.


 The effective size of queue is reduced
 This can be solved once all the elements are dequeued and values of front and rear are
again put back to -1.

The above is solved by using remainder operations as %(maxCapacity)

#include
#define maxCapacity 5

int queue[maxCapacity], front = -1, rear = -1, currSize = 0;

void enQueue(int data){


if(currSize == maxCapacity)
printf("\nMax Size reached can't do enqueue");
else{
if(front == -1){
front = currSize = 0;
rear = maxCapacity - 1;
}

//imagine scenario where enqueue is happening at last element of queue


//if some dequeue has happened then 0th element or others may be free
//using % operation we can now enter at 0th or others positions here
rear = (rear + 1)%maxCapacity;
queue[rear] = data;
currSize = currSize + 1;
printf("%d Successfully Enqueued at array pos:%d\n", data,rear);
}
}
void deQueue(){
if(currSize == 0)
printf("\nNo elements, queue is empty can't dequeue");
else{
printf("\nDequeued : %d", queue[front]);

int item = queue[front];


front = (front + 1)%maxCapacity;
currSize = currSize - 1;

printf("\n%d Successfully dequeued & changed front value which is: at pos:%d\n", item,front);
}
}
void display(){
if(rear == -1)
printf("\nQueue was Empty!!!");
else{
int i;
printf("\nQueue :\n");

for(i=front; i<=rear; i++)


printf("%d ",queue[i]);
}
}

int main()
{
enQueue(2);//front: a[0], rear: a[0]
enQueue(4);//front: a[0], rear: a[1]
enQueue(6);//front: a[0], rear: a[2]
enQueue(8);//front: a[0], rear: a[3]

//front: a[0], rear: a[3]


deQueue();//0th pos now empty, //front: a[1], rear: a[3]
deQueue();//1st pos now empty, //front: a[2], rear: a[3]

//note the explanation in the above image starts from here

enQueue(10);//front: a[2], rear: a[4]

//front: a[2], rear: a[4]

//rear = (rear + 1)%maxCapacity; a[rear] = data;


//rear = (4 + 1)%maxCapacity; i.e. rear = 5%5 = 0, thus, a[0] = 12;
enQueue(12);//front: a[2], rear: a[0]
enQueue(14);//front: a[2], rear: a[1]

deQueue();//2nd pos now empty, front: a[3], rear: a[1]

enQueue(14);//front: a[3], rear: a[2]

return 0;
}

Output:

2 Successfully Enqueued at array pos:0


4 Successfully Enqueued at array pos:1
6 Successfully Enqueued at array pos:2
8 Successfully Enqueued at array pos:3
Dequeued : 2
2 Successfully dequeued and changed front value which is: at pos:1

Dequeued : 4
4 Successfully dequeued & changed front value which is: at pos:2

10 Successfully Enqueued at array pos:4


12 Successfully Enqueued at array pos:0
14 Successfully Enqueued at array pos:1

Dequeued : 6
6 Successfully dequeued & changed front value which is: at pos:3
14 Successfully Enqueued at array pos:2
Applications in Real life scenario and Technologies

There are some real-life examples where we implement a queue. These can be,
 Job scheduling.
 Key board Buffers.
 Request priority of users or consumers in a website or company.
 Round Robin Mechanism.

and lots of things.

Applications in Competitive Programming


If you want to be a competitive coder, enough reasons are there for you to understand every
aspect of queue and apply itto solve problems in a optimised way.

 There are certain problems where you can make your solution optimised regarding time or
space or both with the use of a queue or more.
 Any algorithm that demands for a FIFO holding of variables will be a perfect example for
applications of queue.

Also in Graph theory, you can do whole lot of things using queue, like:
 Breadth First Search with the help of queue.
 Topological sorts.
 Finding shortest paths.
 Ford Fulkerson Algorithm for Maximum flow in a network.
 Level order Traversals for a Tree..

and many more.

Queues using Linked List in C


How to implement Queue using linked list?

Implementation of Queues using Linked List in C solves the problem of Queue


implementation with arrays as using linked list for implementing queue we need not to define the
size of the queue and it can work on the infinite number of values.

Implementing queue using linked list will not change its behavior i.e. the queue will continue
to work with FIFO architecture.

Queue Using Linked List in C


enqueue(data)
 Build a new node with given data.
 Check if the queue is empty or not.
 If queue is empty then assign new node to front and rear.
 Else make next of rear as new node and rear as new node.

dequeue()
 Check if queue is empty or not.
 If queue is empty then dequeue is not possible.
 Else store front in temp
 And make next of front as front.

print()
 Check if there is some data in the queue or not.
 If the queue is empty print “No data in the queue.”
 Else define a node pointer and initialize it with front.
 Print data of node pointer until the next of node pointer becomes NULL.

Algorithm for enqueue(int d)


 STRUCT NODE* NEW_N
 NEW_N->DATA = D
 NEW_N->NEXT = NULL
 IF((FRONT == NULL)&&(REAR == NULL))
 FRONT = REAR = NEW_N
 ELSE
 REAR->NEXT = NEW_N
 REAR = NEW_N

Algorithm for dequeue()


 STRUCT NODE *TEMP
 TEMP = FRONT
 IF((FRONT == NULL)&&(REAR == NULL))
 RETURN
 ELSE
 FRONT = FRONT->NEXT
 FREE(TEMP)

print()
 STRUCT NODE* TEMP
 IF((FRONT == NULL)&&(REAR == NULL))
 RETURN
 ELSE
 TEMP = FRONT
 WHILE(TEMP)
 RETURN TEMP->DATA
 TEMP = TEMP->NEXT

Code for implementing queue using linked list in C

#include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
struct node* next;
};//defining linked list to implement queue

struct node *front = NULL;


struct node *rear = NULL;

void enqueue(int d)//function to insert a node in queue


{
struct node* new_n;
new_n = (struct node*)malloc(sizeof(struct node));
new_n->data = d;
new_n->next = NULL;
if((front == NULL)&&(rear == NULL)){
front = rear = new_n;
}
else{
rear->next = new_n;
rear = new_n;
}
}

void display()//function to display the queue


{
struct node* temp;
if((front == NULL)&&(rear == NULL)){
printf("\nQueue is Empty");
}
else{
temp = front;
while(temp){
printf(" %d ",temp->data);
temp = temp->next;
}
}
}

void dequeue()//function to delete an element from a queue


{
struct node *temp;
temp = front;
if((front == NULL)&&(rear == NULL)){
printf("\nQueue is Empty");
}
else{
front = front->next;
free(temp);
}
}
int main()//main function to use all our declared function
{
enqueue(5);
enqueue(10);
enqueue(15);
enqueue(20);
enqueue(25);
printf("Queue:");
display();
printf("\nQueue After Dequeue:");
dequeue();
display();

Output
Queue: 5 10 15 20 25
Queue After Dequeue: 10 15 20 25

Implementation of Queues using Stack in C


How to implement Queue using Stack?

Implementation of Queues using Stack in C is a process of creating a queue using Stacks. In this
article, we will be using a single stack for the purpose. When a single stack is used for
implementing queues recursive stack call used. This article contains in detail steps and algorithm
for all the functions of queue i.e to insert data, to delete data and to print the data.

enqueue(data)
 In this enqueue function recursively call push() function.
 In this push function check if the stack is full or not
 If the stack is we cannot add more elements.
 Else add the element at top of stack and increase the value of top by 1.

dequeue()
 In this function first we will check if the queue has some element or not.
 If our queue is empty then we cannot delete any element from it.
 Else if there is only one element in the queue we will pop an element from the top of stack.
 Else we will pop all the data from the stack until top reaches to zero and will push back the
removed data after poping the element at top=0.

print()
 Initialize a for loop from zero till the top.
 Print the element at every successful iteration.
 In this way we can display our queue.

Algorithm for enqueue(int x)


 PUSH(X)
push(x)
 VOID PUSH(INT X)
 IF(TOP == N-1)
 RETURN STACK IS FULL
 ELSETOP++
 S[TOP] = X

Algorithm for dequeue()


 IF(TOP == -1)
 RETURN QUEUE IS EMPTY
 ELSE IF(TOP == 0)
 RETURN POP()
 DATA = POP()
 RES =DEQUEUE()
 PUSH(DATA)
 RETURN RES

pop()
 RETURN S[TOP–]
 Algorithm for print()
 FOR I=0 TO TOP
 RETURN S[I]

Code for implementing queue using stack in C

#include<stdio.h>
#include<stdlib.h>

#define N 20 //defining the size of queue

int s[N], top = -1;

int pop () //function to remove an element from stack


{
return s[top--];
}

void push (int x) //function to insert an element into stack


{
if (top == N - 1)
printf ("Stack is Full");
else
{
top++;
s[top] = x;
}
}

void enqueue (int x)


{
push (x);
}

void display () //function to print elements of a queue


{
int i;
for (i = 0; i <= top; i++)
printf (" %d ", s[i]);
}

int dequeue ()
{
int data, res;
if (top == -1)
printf ("Queue is Empty");
else if (top == 0)
return pop ();
data = pop ();
res = dequeue ();
push (data);
return res;

int main ()
{
enqueue (5);
enqueue (10);
enqueue (15);
enqueue (20);
enqueue (25);
printf ("Queue:");
display ();
printf ("\nQueue After Dequeue:");
dequeue ();
display ();

Output
Queue: 5 10 15 20 25
Queue After Dequeue: 10 15 20 25

Implementation of Queue using two stacks in C

Queue using two Stack in C


Qeue and stack are fundamentally two different linear data structures, but given with one or more
of any one data structures, we can just convert it into other and apply it in real. Here, in this
section we will learn, Implementation of Queue using two stacks in C. We will built enqueue
operation, dequeue operation functions using stacks.

Implementation of Queue using two stacks in C

Algorithm:
 We take two stacks say stack1 and stack2.
 stack1 will be working as the main queue and stack2 will help us in reversing the order of
stack1.
 For enqueue operation, we will simply push the element let say x into stack1.
 For dequeue operation,
o If both the stack1 and stack2 are empty then we need to print that queue is empty.
o If stack2 is empty then we need to push all the elements from stack1 to stack2 .
o Pop the element from stack2 and return it.

#include <stdio.h>
#include<stdlib.h>

#define N 100 // size for arrays representing stack1 and stack2

int stack1[N], stack2[N]; // array representing stacks of size N

int top_stack1 = -1; // top for stack1


int top_stack2 = -1; // top for stack2

int count = 0; // For keeping the count of element present in queue

void push_stack1 (int data)


{
if (top_stack1 == N - 1)
{
printf ("Stack1 is overflow");
return;
}

else
{
top_stack1++;
stack1[top_stack1] = data;
}

return;
}

void push_stack2 (int data)


{
if (top_stack2 == N - 1)
{
printf ("Stack2 is overflow");
return;
}
else
{
top_stack2++;
stack2[top_stack2] = data;
}

return;

int pop_stack1 ()
{
if (top_stack1 == -1)
{
printf ("Stack1 is underflow\n");
return -1;
}

return stack1[top_stack1--];
}

int pop_stack2 ()
{

if (top_stack2 == -1)
{
printf ("Stack2 is underflow\n");
return -1;
}

return stack2[top_stack2--];

void enqueue (int data)


{
push_stack1 (data);
count++;

void dequeue ()
{
if (top_stack1 == -1 && top_stack2 == -1)
printf ("Queue is empty\n");

else
{
for (int i = 0; i < count; i++)
{

int temp = pop_stack1 ();


push_stack2 (temp);
}
int x = pop_stack2 ();

printf ("Dequeued element is %d\n", x);


count--;

for (int i = 0; i < count; i++)


{

int temp = pop_stack2 ();


push_stack1 (temp);

}
}
}

void display ()
{
if (top_stack1 == -1)
{
printf ("Queue is empty \n");
return;
}

for (int i = 0; i < top_stack1; i++)


printf ("%d ", stack1[i]);

printf ("\n");

void top ()
{
printf ("Top element of queue is %d ", stack1[0]);
}

int main ()
{

enqueue (3);
enqueue (45);
enqueue (-1);

display ();

dequeue ();

display ();

return 0;

Output:

Elements in queue : 3 45 -1
Deleted element : 3

Elements in queue : 45 -1

You might also like