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

Lecture 5 Queue DSA

The document provides an overview of queues as a data structure, explaining its characteristics, operations (enqueue, dequeue, peek, isEmpty, full), and implementations using arrays and linked lists. It discusses the differences between linear and circular arrays, as well as the efficiency of linked list implementations. Additionally, it outlines time complexities for various operations and mentions applications of queues in task scheduling and data transfer.

Uploaded by

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

Lecture 5 Queue DSA

The document provides an overview of queues as a data structure, explaining its characteristics, operations (enqueue, dequeue, peek, isEmpty, full), and implementations using arrays and linked lists. It discusses the differences between linear and circular arrays, as well as the efficiency of linked list implementations. Additionally, it outlines time complexities for various operations and mentions applications of queues in task scheduling and data transfer.

Uploaded by

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

DATA STRUCTURES

AND ALGORITHMS
QUEUE

Ali Mobin Memon


What is Queue?

• Its Linear / non-linear data structure. But it cannot be both at the


same time

• Its Static and Dynamic. But it cannot be both at the same time

• Its continuous as well as non-continuous stream of data. But it


cannot be both at the same time

• Depends on way it is executed

• Via linked list

• Via Array

• Via Array Circular (Will Discuss in coming slides)


What is Queue
• It follows FIFO ( First in first out )

• The first come first served basis, like in restaurant

• It features two operations

• Enqueue
Means to insert a new item

• Dequeue
Means to delete an item
Queue Operations
• Key Operations:

• Enqueue: Add an element to the rear of the Queue.

• Dequeue: Remove the element from the front of the


Queue.

• Peek: Look at the front element of the queue without


removing it.

• is Empty: Check if the Queue is empty.

• Full: Checks if the queue is full.


Queue Operations
Applications in DSA

• Task scheduling in operating systems

• Data transfer in network communication

• Simulation of real-world systems (e.g., waiting lines)

• Priority queues for event processing queues for event processing


Queue Operations
Implementation via Array
Please note that a simple array implementation discussed
here is not used in practice as it is not efficient. In
practice, we either use

1. Linked List Implementation of Queue.

2. Circular array implementation of queue.


Queue Implementation via Array

1. Create an array arr of size n

2. Take two variables front and rear which are initialized as 0


and -1 respectively

3. Rear is the index up to which the elements are stored in the


array including the rear index itself. We mainly add an item
by incrementing it.

4. Front is the index of the first element of the array. We mainly


remove the element at this index in Dequeue operation.
Queue Implementation via Array
import java.util.*; void dequeue() {
// If the queue is empty
class Queue { if (front > rear) {
int front, rear, capacity; System.out.println("Queue is empty");
int[] queue; return;
}
// Constructor to initialize the queue // Shift all elements from index 1 till rear to the
Queue(int c) { left by one
front = 0; for (int i = 0; i < rear; i++) {
rear = -1; queue[i] = queue[i + 1];
capacity = c; }
queue = new int[capacity]; // Decrement rear
} rear--;
}
// Function to insert an element at the rear of
the queue void display() {
if (front > rear) {
void enqueue(int data) { System.out.println("Queue is Empty");
// Check if the queue is full return;
if (rear == capacity - 1) { }
System.out.println("Queue is full"); // Traverse front to rear and print elements
return; for (int i = front; i <= rear; i++) {
} System.out.print(queue[i] + " <-- ");
}
// Insert element at the rear }
queue[++rear] = data;
}
// Function to print the front of the queue public static void main(String[] args) {
void front() { Queue q = new Queue(4); // queue of
if (rear == -1) { capacity 4
System.out.println("Queue is Empty");
return; // Insert element in the queue
} q.enqueue(60);
System.out.println("Front Element is: " +
queue[front]); // Print queue elements
} q.display();

// Dequeue elements
q.dequeue();
q.dequeue();

System.out.println("After two node


deletions");
System.out.println("After one insertion");

q.enqueue(60);

// Print queue elements


q.display();

// Print front of the queue


q.front();

}
Queue Time Complexity via Array
• O(1) for insertion as we simply increment a pointer value
and insert value in array

• O(N) for removing element as we use for loop to


implement that. Shocking right ?

• For Enqueue and Dequeue it should be BIG O(1) for array


implementation but its not

• Hence, we use Circular array implementation

• Auxiliary Space: O(N), as here we are using an N size


array for implementing Queue
Queue Operations
Circular Array Queue
• A Circular Queue is an extended version of a normal
queue

• where the last element of the queue is connected to the


first element of the queue forming a circle.

• The operations are performed based on FIFO (First In First


Out) principle.

• It is also called ‘Ring Buffer’.


Queue Operations
Circular Array Queue Operations
• Front: Get the front item from the queue.

• Rear: Get the last item from the queue.

• EnQueue(value) This function is used to insert an element


into the circular queue. In a circular queue, the new
element is always inserted at the rear position.

• Check whether the queue is full – [i.e., the rear end is in


just before the front end in a circular manner].

• If it is full then display Queue is full.

• If the queue is not full then, insert an element at the


end of the queue.
Queue Operations
Circular Array Queue Operations
• Dequeue(): This function is used to delete an element
from the circular queue. In a circular queue, the element is
always deleted from the front position.

• Check whether the queue is Empty.

• If it is empty, then display Queue is empty.

• If the queue is not empty, then get the last element


and remove it from the queue.
Queue Operations
Circular Array Queue Operations
Queue Operations
Circular Array Queue Implementation
• Initialize an array queue of size n,

• where n is the maximum number of elements that the


queue can hold.

• Initialize two variables front and rear to -1.

• Enqueue: Increment rear by 1.

• If rear is equal to n, set rear to 0.

• If front is -1, set front to 0.

• Set queue[rear] to x.
Queue Operations
Circular Array Queue Implementation

• Dequeue: Check if the queue is empty by checking if front is -1.

• If it is, return an error message indicating that the queue is empty.

• Set x to queue[front].

• If front is equal to rear, set front and rear to -1.

• Otherwise, increment front by 1 and if front is equal to n, set front


to 0.

• Return x.
import java.util.ArrayList;

class CircularQueue{

// Declaring the class variables.


private int size, front, rear;

// Declaring array list of integer type.


private ArrayList<Integer> queue = new
ArrayList<Integer>();

// Constructor
CircularQueue(int size)
{
this.size = size;
this.front = this.rear = -1;
}
//Enqueue else
public void enQueue(int data) {
{ rear = (rear + 1);
// Condition if queue is full.
// Adding a new element if
if((front == 0 && rear == size - 1) ||
if(front <= rear)
(rear == (front - 1) % (size - 1)))
{ {
System.out.print("Queue is queue.add(rear, data);
Full");
}
}
// Else updating old value
// condition for empty queue.
else if(front == -1) else
{ {
front = 0; queue.set(rear, data);
rear = 0; }
queue.add(rear, data);
}
}
}
else if(rear == size - 1 && front !=
0)
{
rear = 0;
queue.set(rear, data);
}
//Dequeue else if(front == size - 1)
public int deQueue() {
{ front = 0;
int temp;
}

// Condition for empty queue. else


if(front == -1) {
{ front = front + 1;
System.out.print("Queue is
}
Empty");

// Return -1 in case of empty // Returns the dequeued element


queue
return temp;
return -1;
} }

temp = queue.get(front);

// Condition for only one element


if(front == rear)
{
front = -1;
rear = -1;
}
public void displayQueue() // If rear crossed the max index and indexing has
started in loop
{
else
// Condition for empty queue.
{
if(front == -1)
// Loop for printing elements from front to max size
{ or last index
System.out.print("Queue is Empty"); for(int i = front; i < size; i++)
return; {
} System.out.print(queue.get(i));
// If rear has not crossed the max size or queue System.out.print(" ");
rear is still
}
greater then front.
// Loop for printing elements from 0th index till rear
System.out.print("Elements in the " + "circular position
queue are: ");
for(int i = 0; i <= rear; i++)
if(rear >= front)
{
{
System.out.print(queue.get(i));
// Loop to print elements from front to rear.
System.out.print(" ");
for(int i = front; i <= rear; i++)
}
{
System.out.println();
System.out.print(queue.get(i));
}
}
}
}
public static void main(String[] args) x = q.deQueue();
{
// Checking for empty queue.
// Initialising new object of CircularQueue class.
if(x != -1)
CircularQueue q = new CircularQueue(5);
{
System.out.print("Deleted value = ");
q.enQueue(14);
System.out.println(x);
q.enQueue(22);
}
q.enQueue(13);
q.enQueue(-6);
q.displayQueue();

q.displayQueue();
q.enQueue(9);
q.enQueue(20);
int x = q.deQueue();
q.enQueue(5);

// Checking for empty queue.


q.displayQueue();
if(x != -1)
{
q.enQueue(20);
System.out.print("Deleted value = ");
}
System.out.println(x);
}
}
Queue Operations
Circular Array Queue Time Complexity

• O(1) for insertion as we simply increment a pointer value and


insert value in array

• O(1) for removing element as we use for loop to implement


that.

• For Enqueue and Dequeue it is BIG O(1) for array now

• Auxiliary Space: O(N), as here we are using an N size array


for implementing Queue
Queue Operations
Linked List Queue

• As we have discussed before Array Queue is not efficient as for


deletion its Big O(N) which is not acceptable

• We use Circular Array Queue Implementation

• Or We use Linked list Queue Implementation


Queue Operations
Linked List Queue Operations

• If Linked List is empty print -1 just like in stack array top


= -1

• We maintain two pointers, front, and rear. The front points


to the first item of the queue and rear points to the last
item.

• Enqueue(): This operation adds a new node after the rear


and moves the rear to the next node.

• Dequeue(): This operation removes the front node and


moves the front to the next node.
Queue Operations
Linked List Queue Implementation
• Create a class QNode with data members integer data and
QNode* next

• A parameterized constructor that takes an integer x value


as a parameter and sets data equal to x and next as NULL

• Create a class Queue with data members QNode front and


rear

• Enqueue Operation with parameter x:

• Initialize QNode* temp with data = x

• If the rear is set to NULL, then set the front and rear to
temp and return(Base Case)

• Else set rear next to temp and then move rear to temp
Queue Operations
Linked List Queue Implementation

• Dequeue Operation:

• If the front is set to NULL return(Base Case)

• Initialize QNode temp with front and set front to its next

• If the front is equal to NULL, then set the rear to NULL

• Delete temp from the memory


Queue Operations
Linked List Queue Implementation
// Node class representing a single node in the linked list
class Node {
int data;
Node next;

Node(int new_data) {
this.data = new_data;
this.next = null;
}
}
// Class to implement queue operations // Function to add an element to the queue
using a linked list
void enqueue(int new_data) {
class Queue {

// Create a new linked list node


// Pointer to the front and the rear of the
linked list Node new_node = new Node(new_data);

Node front, rear;


// If queue is empty, the new node is both the
front and rear
// Constructor to initialize the front and
rear if (rear == null) {

Queue() { front = rear = null; } front = rear = new_node;


return;

// Function to check if the queue is empty }

boolean isEmpty() {
// Add the new node at the end of the queue and
change rear
// If the front and rear are null, then the
queue is empty, otherwise it's not rear.next = new_node;
rear = new_node;

return front == null && rear == null; }

}
// Function to remove an element from the // Function to get the front element of the queue
queue
int getFront() {
void dequeue() {
// Checking if the queue is empty
if (isEmpty()) {
// If queue is empty, return
System.out.println("Queue is empty");
if (isEmpty()) { return Integer.MIN_VALUE;
System.out.println("Queue Underflow"); }
return; return front.data;
} }

// Store previous front and move front one // Function to get the rear element of the queue
node ahead
int getRear() {
Node temp = front;
front = front.next;
// Checking if the queue is empty
if (isEmpty()) {
If front becomes null, then change rear also to
null System.out.println("Queue is empty");
if (front == null) { return Integer.MIN_VALUE;

rear = null; }

} return rear.data;

} }
}
// Driver code to test the queue implementation // Dequeue an element from the queue
public class Main { q.dequeue();
public static void main(String[] args) {
Queue q = new Queue();
System.out.println("Queue Front: " +
q.getFront());
// Enqueue elements into the queue System.out.println("Queue Rear: " +
q.enqueue(10); q.getRear());

q.enqueue(20); }
}
System.out.println("Queue Front: " +
q.getFront());
System.out.println("Queue Rear: " +
q.getRear());

// Dequeue elements from the queue


q.dequeue();
q.dequeue();

// Enqueue more elements into the queue


q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
Queue Operations
Linked List Queue Time Complexity
• Its O(1),

• The time complexity of both operations enqueue()

• Dequeue() is O(1) as it only changes a few pointers in both


operations

• Auxiliary Space: O(1),

• The auxiliary Space of both operations enqueue() and


dequeue() is O(1) as constant extra space is required
Next Week

• 1 hour test before break

• Data structure

• Array

• linked list

• Queue

• Assignment 1 announcement

• To be decided that day

• Deadline: 2 weeks after announcement


Reference

• Geek for Geeks

• CHAT-GPT

• Prep insta
THANK YOU

You might also like