Time and Space Complexity Analysis of Queue operations
Last Updated :
31 Jan, 2024
What is Queue?
Queue is a linear data structure that follows FIFO approach (First In First Out). One can imagine a queue as a line of people waiting in sequential order which starts from the beginning of the line. It is an ordered list in which insertions are done at one end which is known as the rear and deletions are done from the other end known as the front. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. A queue can be implemented using Arrays or Linked Lists.
Complexity analysis of different Queue operations:
1) enqueue():
This operation inserts an element at the back of the queue. It takes one parameter, the value that is to be inserted at the back of the queue.
Below is the implementation of enqueue() using Array:
C++
#include <iostream>
using namespace std;
#define capacity 10
class Queue {
public:
int queue[capacity];
int front;
int rear;
Queue()
{
front = -1;
rear = -1;
}
void enqueue(int val)
{
if (front == -1) {
front++;
}
if (rear == capacity - 1) {
cout << "Queue overflow!!!\n";
return;
}
queue[++rear] = val;
cout << val << " inserted successfully\n";
}
};
int main()
{
Queue q;
// Inserting elements in the queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
return 0;
}
Java
// Java code to perform enqueue using array
import java.io.*;
class GFG {
static final int capacity = 10;
static class Queue {
int queue[] = new int[capacity];
int front;
int rear;
void Queue()
{
front = -1;
rear = -1;
}
void enqueue(int val)
{
if(front==-1)
{
front++;
}
if(rear==capacity-1)
{
System.out.println("Queue overflow!!!");
return;
}
queue[++rear] = val;
System.out.println(val + " inserted successfully");
}
}
public static void main(String[] args)
{
Queue q = new Queue();
//Inserting elements in queue
//using enqueue operation
q.enqueue(1);
q.enqueue(2);
}
}
// This code is contributed by adityapatil12
Python
# Python code for inserting elements in queue
class Queue:
def __init__(self):
self.queue = [None] * 10
self.front = -1
self.rear = -1
def enqueue(self, val):
if self.front == -1:
self.front += 1
if self.rear == 9:
print("Queue overflow!!!")
return
self.queue[self.rear] = val
self.rear += 1
print("{} inserted successfully".format(val))
q = Queue()
# Inserting elements in the queue
# using enqueue operation
q.enqueue(1)
q.enqueue(2)
# This code is contributed by adityamaharshi21
C#
// Include namespace system
using System;
public class GFG
{
public const int capacity = 10;
class Queue
{
public int[] queue = new int[GFG.capacity];
public int front;
public int rear;
public void enqueue(int val)
{
if (this.front == -1)
{
this.front++;
}
if (this.rear == GFG.capacity - 1)
{
Console.WriteLine("Queue overflow!!!");
return;
}
this.queue[++this.rear] = val;
Console.WriteLine(val.ToString() + " inserted successfully");
}
}
public static void Main(String[] args)
{
var q = new Queue();
// Inserting elements in queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
}
}
// This code is contributed by aadityaburujwale.
JavaScript
// JS code for above operation
class Queue {
constructor() {
this.queue = [];
this.front = -1;
this.rear = -1;
this.capacity=10
}
enqueue(val) {
if (this.front == -1) {
this.front++;
}
if (this.rear == this.capacity-1) {
console.log("Queue overflow!!!");
}
this.queue[++(this.rear)] = val;
console.log(val, " inserted successfully");
}
};
let q = new Queue();
// Inserting elements in the queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
// This code is contributed by adityamaharshi21
Output1 inserted successfully
2 inserted successfully
Complexity Analysis:
- Time Complexity: O(1), In enqueue function a single element is inserted at the last position. This takes a single memory allocation operation which is done in constant time.
- Auxiliary Space: O(1). As no extra space is being used.
Below is the implementation of enqueue() using Linked List :
C++
#include <iostream>
using namespace std;
class node {
public:
int data;
node* next;
node(int val)
{
data = val;
next = NULL;
}
};
class Queue {
public:
node* front;
node* rear;
Queue()
{
front = rear = NULL;
}
void enqueue(int val)
{
// if queue is empty
if (rear == NULL) {
// Create a new node as rear
rear = new node(val);
rear->next = NULL;
rear->data = val;
// Front will be rear as only
// one element exist in queue
front = rear;
}
else {
// Create temp node of val value
node* temp = new node(val);
// Add temp after the rear of queue
rear->next = temp;
// Update temp as the end element
rear = temp;
}
cout << val << " inserted successfully \n";
}
};
int main()
{
Queue q;
// Inserting elements in the queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
return 0;
}
Java
// Java code for above approach
class Node {
public int data;
public Node next;
public Node(int val)
{
data = val;
next = null;
}
}
class Queue {
public Node front;
public Node rear;
public Queue() { front = rear = null; }
public void enqueue(int val)
{
// If queue is empty
if (rear == null) {
// Create a new node as rear
rear = new Node(val);
rear.next = null;
rear.data = val;
// Front will be rear as only
// one element exist in queue
front = rear;
}
else {
// Create temp node of val value
Node temp = new Node(val);
// Add temp after the rear of queue
rear.next = temp;
// Update temp as the end element
rear = temp;
}
System.out.println(val + " inserted successfully");
}
}
public class Main {
public static void main(String[] args)
{
Queue q = new Queue();
// Inserting elements in the queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
}
}
// This code is contributed by adityamaharshi21
Python
# Python program for above approach
class node:
def __init__(self, val):
self.data = val
self.next = None
class Queue:
def __init__(self):
# If queue is empty
self.front = self.rear = None
def enqueue(self, val):
if self.rear == None:
# Create a new node as rear
self.rear = node(val)
self.rear.next = None
self.rear.data = val
# Front will be rear as only
# one element exist in queue
self.front = self.rear
else:
# Create temp node of val value
temp = node(val)
# Add temp after the rear of queue
self.rear.next = temp
# Update temp as the end element
self.rear = temp
print(val, "inserted successfully")
q = Queue()
# Inserting elements in the queue
# using enqueue operation
q.enqueue(1)
q.enqueue(2)
# This code is contributed by adityamaharshi21
C#
using System;
class Node {
public int data;
public Node next;
public Node(int val)
{
data = val;
next = null;
}
}
class Queue {
public Node front;
public Node rear;
public Queue() { front = rear = null; }
public void enqueue(int val)
{
// If queue is empty
if (rear == null)
{
// Create a new node as rear
rear = new Node(val);
rear.next = null;
rear.data = val;
// Front will be rear as only
// one element exist in queue
front = rear;
}
else
{
// Create temp node of val value
Node temp = new Node(val);
// Add temp after the rear of queue
rear.next = temp;
// Update temp as the end element
rear = temp;
}
Console.WriteLine(val + " inserted successfully");
}
}
class MainClass {
public static void Main(string[] args)
{
Queue q = new Queue();
// Inserting elements in the queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
}
}
// This code is contributed by aadityamaharshi21.
JavaScript
// Javascript code for inserting elements in a Queue using Linked List
class node {
constructor(val) {
this.data = val;
this.next = null;
}
}
class Queue {
constructor() {
this.front = this.rear = null;
}
enqueue(val) {
// if queue is empty
if (this.rear === null) {
// Create a new node as rear
this.rear = new node(val);
this.rear.next = null;
this.rear.data = val;
// Front will be rear as only
// one element exist in queue
this.front = this.rear;
} else {
// Create temp node of val value
let temp = new node(val);
// Add temp after the rear of queue
this.rear.next = temp;
// Update temp as the end element
this.rear = temp;
}
console.log(`${val} inserted successfully`);
}
}
let q = new Queue();
// Inserting elements in the queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
// This code is contributed by adityamaharshi21
Output1 inserted successfully
2 inserted successfully
Complexity Analysis:
- Time Complexity: O(1). Only a new node is created and the pointer of the last node is updated. This includes only memory allocation operations. Hence it can be said that insertion is done in constant time.
- Auxiliary Space: O(1). No extra space is used.
2) dequeue():
This operation removes an element present at the front of the queue. Also, it results in an error if the queue is empty.
Below is the implementation of dequeue() using Array :
C++
#include <iostream>
using namespace std;
#define capacity 10
class Queue {
public:
int queue[capacity];
int front;
int rear;
Queue()
{
front = -1;
rear = -1;
}
void enqueue(int val)
{
if (front == -1) {
front++;
}
if (rear == capacity - 1) {
cout << "Queue overflow!!!\n";
return;
}
queue[++rear] = val;
}
void dequeue()
{
if (front == -1 || front > rear) {
cout << "Queue is empty!!!\n";
return;
}
cout << "Element deleted from queue : " << queue[front++] << "\n";
}
};
int main()
{
Queue q;
// Inserting elements in the queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
// Deleting elements from the queue
// using dequeue operation
q.dequeue();
return 0;
}
Java
import java.io.*;
class GFG {
static final int capacity = 10;
static class Queue {
int queue[] = new int[capacity];
int front;
int rear;
void Queue()
{
front = -1;
rear = -1;
}
void enqueue(int val)
{
if (front == -1) {
front++;
}
if (rear == capacity - 1) {
System.out.println("Queue overflow!!!");
return;
}
queue[++rear] = val;
}
void dequeue()
{
if (front == -1 || front > rear) {
System.out.println("Queue is empty!!!");
}
System.out.println(
"Element deleted from queue : "
+ queue[front + 1]);
}
}
public static void main(String[] args)
{
Queue q = new Queue();
// Inserting elements in the queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
// Deleting elements from the queue
// using dequeue operation
q.dequeue();
}
}
// This code is contributed by adityamaharshi21
Python
# Python code for element deletion from queue
class Queue:
def __init__(self):
self.queue = [None] * 10
self.front = -1
self.rear = -1
def enqueue(self, val):
if self.front == -1:
self.front += 1
if self.rear == len(self.queue) - 1:
print("Queue overflow!!!")
return
self.queue[self.rear + 1] = val
self.rear += 1
def dequeue(self):
if self.front == -1 or self.front > self.rear:
print("Queue is empty!!!")
return
print("Element deleted from queue:", self.queue[self.front])
self.front += 1
q = Queue()
# Inserting elements in the queue
# using enqueue operation
q.enqueue(1)
q.enqueue(2)
# Deleting elements from the queue
# using dequeue operation
q.dequeue()
# This code is contributed by adityamaharshi21
C#
// Include namespace system
using System;
public class GFG {
public const int capacity = 10;
class Queue {
public int[] queue = new int[GFG.capacity];
public int front;
public int rear;
public void enqueue(int val)
{
if (this.front == -1) {
this.front++;
}
if (this.rear == GFG.capacity - 1) {
Console.WriteLine("Queue overflow!!!");
return;
}
this.queue[++this.rear] = val;
}
public void dequeue()
{
if (this.front == -1
|| this.front > this.rear) {
Console.WriteLine("Queue is empty!!!");
}
Console.WriteLine(
"Element deleted from queue : "
+ this.queue[this.front + 1]);
}
}
public static void Main(String[] args)
{
var q = new Queue();
// Inserting elements in queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
// Deleting elements in queue
// using dequeue operation
q.dequeue();
}
}
JavaScript
class Queue {
constructor() {
this.queue = [];
this.front = -1;
this.rear = -1;
this.capacity = 10;
}
enqueue(val) {
if (this.front == -1) {
this.front++;
}
if (this.rear == (this.capacity)-1) {
console.log("Queue overflow!!!");
}
this.queue[++(this.rear)] = val;
}
dequeue() {
if (this.front == -1 || this.front > this.rear) {
console.log("Queue is empty!!!");
}
console.log("Element deleted from queue : ", this.queue[(this.front)++]);
}
};
let q = new Queue();
// Inserting elements in the queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
// Deleting elements from the queue
// using dequeue operation
q.dequeue();
// This code is contributed by adityamaharsh21
OutputElement deleted from queue : 1
Complexity Analysis:
- Time Complexity: O(1). In array implementation, only an arithmetic operation is performed i.e., the front pointer is incremented by 1. This is a constant time function.
- Auxiliary Space: O(1). No extra space is utilized for deleting an element from the queue.
Below is the implementation of dequeue using Linked List :
C++
#include <iostream>
using namespace std;
#define capacity 10
class node {
public:
int data;
node* next;
node(int val)
{
data = val;
next = NULL;
}
};
class Queue {
public:
node* front;
node* rear;
Queue()
{
front = rear = NULL;
}
void enqueue(int val)
{
// if queue is empty
if (rear == NULL) {
// Create a new node as rear
rear = new node(val);
rear->next = NULL;
rear->data = val;
// Front will be rear as only
// one element exist in queue
front = rear;
}
else {
// Create temp node of val value
node* temp = new node(val);
// Add temp after the rear of queue
rear->next = temp;
// Update temp as the end element
rear = temp;
}
}
void dequeue()
{
// point temp to front of queue
node* temp = front;
// if queue is empty
if (front == NULL) {
cout << "Underflow" << endl;
return;
}
else if (temp->next != NULL) {
temp = temp->next;
cout << "Element deleted from queue is : " << front->data << endl;
free(front);
front = temp;
}
// if queue consist of only one element
else {
cout << "Element deleted from queue is : " << front->data << endl;
free(front);
front = NULL;
rear = NULL;
}
}
};
int main()
{
Queue q;
// Inserting elements using
// enqueue operation
q.enqueue(5);
q.enqueue(7);
// Removing elements from queue
// using dequeue operation
q.dequeue();
return 0;
}
Java
import java.util.Scanner;
class Node {
public int data;
public Node next;
public Node(int val) {
data = val;
next = null;
}
}
class Queue {
public Node front;
public Node rear;
public Queue() {
front = rear = null;
}
public void enqueue(int val) {
// if queue is empty
if (rear == null) {
// Create a new node as rear
rear = new Node(val);
rear.next = null;
rear.data = val;
// Front will be rear as only
// one element exist in queue
front = rear;
}
else {
// Create temp node of val value
Node temp = new Node(val);
// Add temp after the rear of queue
rear.next = temp;
// Update temp as the end element
rear = temp;
}
}
public void dequeue() {
// point temp to front of queue
Node temp = front;
// if queue is empty
if (front == null) {
System.out.println("Underflow");
return;
}
else if (temp.next != null) {
temp = temp.next;
System.out.println("Element deleted from queue is: " + front.data);
front = temp;
}
// if queue consist of only one element
else {
System.out.println("Element deleted from queue is: " + front.data);
front = null;
rear = null;
}
}
}
public class Main {
public static void main(String[] args) {
Queue q = new Queue();
// Inserting elements using
// enqueue operation
q.enqueue(5);
q.enqueue(7);
// Removing elements from queue
// using dequeue operation
q.dequeue();
}
}
Python
class node:
def __init__(self, val):
self.data = val
self.next = None
class Queue:
def __init__(self):
self.front = self.rear = None
def enqueue(self, val):
# if queue is empty
if self.rear == None:
# Create a new node as rear
self.rear = node(val)
self.rear.next = None
self.rear.data = val
# Front will be rear as only
# one element exist in queue
self.front = self.rear
else:
# Create temp node of val value
temp = node(val)
# Add temp after the rear of queue
self.rear.next = temp
# Update temp as the end element
self.rear = temp
def dequeue(self):
# point temp to front of queue
temp = self.front
# if queue is empty
if self.front == None:
print("Underflow")
return
elif temp.next != None:
temp = temp.next
print("Element deleted from queue is : ", self.front.data)
self.front = temp
# if queue consist of only one element
else:
print("Element deleted from queue is : ", self.front.data)
self.front = None
self.rear = None
q = Queue()
# Inserting elements using
# enqueue operation
q.enqueue(5)
q.enqueue(7)
# Removing elements from queue
# using dequeue operation
q.dequeue()
C#
using System;
class Node {
public int data;
public Node next;
public Node(int val)
{
data = val;
next = null;
}
}
class Queue {
public Node front;
public Node rear;
public Queue() { front = rear = null; }
public void enqueue(int val)
{
// if queue is empty
if (rear == null) {
// Create a new node as rear
rear = new Node(val);
rear.next = null;
rear.data = val;
// Front will be rear as only
// one element exist in queue
front = rear;
}
else {
// Create temp node of val value
Node temp = new Node(val);
// Add temp after the rear of queue
rear.next = temp;
// Update temp as the end element
rear = temp;
}
}
public void dequeue()
{
// point temp to front of queue
Node temp = front;
// if queue is empty
if (front == null) {
Console.WriteLine("Underflow");
return;
}
else if (temp.next != null) {
temp = temp.next;
Console.WriteLine(
"Element deleted from queue is: "
+ front.data);
front = temp;
}
// if queue consist of only one element
else {
Console.WriteLine(
"Element deleted from queue is: "
+ front.data);
front = null;
rear = null;
}
}
}
public class MainClass {
public static void Main()
{
Queue q = new Queue();
// Inserting elements using
// enqueue operation
q.enqueue(5);
q.enqueue(7);
// Removing elements from queue
// using dequeue operation
q.dequeue();
}
}
// This code is contributed adityamaharshi21.
JavaScript
//Javascript program for above approach
const capacity = 10;
// Define the node class
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
// Define the Queue class
class Queue {
constructor() {
this.front = this.rear = null;
}
// Method to enqueue element in the queue
enqueue(val) {
// If queue is empty
if (this.rear == null) {
// Create a new node as rear
this.rear = new Node(val);
this.rear.next = null;
this.rear.data = val;
// Front will be rear as only one element exist in queue
this.front = this.rear;
}
else {
// Create temp node of val value
let temp = new Node(val);
// Add temp after the rear of queue
this.rear.next = temp;
// Update temp as the end element
this.rear = temp;
}
}
// Method to dequeue element from the queue
dequeue() {
// Point temp to front of queue
let temp = this.front;
// If queue is empty
if (this.front == null) {
console.log("Underflow");
return;
} else if (temp.next != null) {
temp = temp.next;
console.log("Element deleted from queue is : " + this.front.data);
this.front = temp;
}
// If queue consist of only one element
else {
console.log("Element deleted from queue is : " + this.front.data);
free(this.front);
this.front = null;
this.rear = null;
}
}
}
// Driver Code
let q = new Queue();
// Inserting elements using enqueue operation
q.enqueue(5);
q.enqueue(7);
// Removing elements from queue using dequeue operation
q.dequeue();
// This code is contributed by adityamaharshi21
OutputElement deleted from queue is : 5
Complexity Analysis:
- Time Complexity: O(1). In dequeue operation, only the first node is deleted and the front pointer is updated. This is a constant time operation.
- Auxiliary Space: O(1). No extra space is utilized for deleting an element from the queue.
3) peek():
This operation prints the element present at the front of the queue.
Below is the implementation of peek() using Array:
C++
#include <iostream>
using namespace std;
#define capacity 10
class Queue {
public:
int queue[capacity];
int front;
int rear;
Queue()
{
front = -1;
rear = -1;
}
void enqueue(int val)
{
if (front == -1) {
front++;
}
if (rear == capacity - 1) {
cout << "Queue overflow!!!\n";
return;
}
queue[++rear] = val;
}
void peek()
{
if (front == -1 || front > rear) {
cout << "Queue is empty !\n";
return;
}
cout << "Element at the front of queue: " << queue[front] << "\n";
}
};
int main()
{
Queue q;
// Inserting elements in the queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
// Printing front element
// using peek operation
q.peek();
return 0;
}
Java
// Java code for peek operation
import java.io.*;
class GFG {
static final int capacity = 10;
static class Queue {
int queue[] = new int[capacity];
int front;
int rear;
void Queue()
{
front = 0;
rear = -1;
}
void enqueue(int val)
{
if (front == 0) {
front = front + 1;
}
if (rear == capacity - 1) {
System.out.println("Queue overflow!!!");
return;
}
queue[rear = rear + 1] = val;
}
void peek()
{
if (front == -1 || front > rear) {
System.out.println("Queue is empty!");
return;
}
System.out.println(
"Element at the front of queue: "
+ queue[front]);
}
}
public static void main(String[] args)
{
Queue q = new Queue();
// Inserting elements in queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
// Printing front element
// using peek operation
q.peek();
}
}
// This code is contributed by adityamaharshi21
Python
CAPACITY = 10
class Queue:
def __init__(self):
self.queue = [None] * CAPACITY
self.front = -1
self.rear = -1
def enqueue(self, val):
if self.front == -1:
self.front += 1
if self.rear == CAPACITY - 1:
print("Queue overflow!!!")
return
self.queue[self.rear + 1] = val
self.rear += 1
def peek(self):
if self.front == -1 or self.front > self.rear:
print("Queue is empty !")
return
print("Element at the front of queue:",self.queue[self.front])
q = Queue()
# Inserting elements in the queue
# using enqueue operation
q.enqueue(1)
q.enqueue(2)
# Printing front element
# using peek operation
q.peek()
# This code is contributed by aadityamaharshi21.
C#
// Include namespace system
using System;
public class GFG {
public const int capacity = 10;
class Queue {
public int[] queue = new int[GFG.capacity];
public int front;
public int rear;
public Queue()
{
this.front = -1;
this.rear = -1;
}
public void enqueue(int val)
{
if (this.front == -1) {
this.front++;
}
if (this.rear == GFG.capacity - 1) {
Console.WriteLine("Queue overflow!!!");
return;
}
this.queue[++this.rear] = val;
}
public void peek()
{
if (this.front == -1
|| this.front > this.rear) {
Console.WriteLine("Queue is empty!!!");
return;
}
Console.WriteLine(
"Element at the front of queue: "
+ this.queue[this.front]);
}
}
public static void Main(String[] args)
{
var q = new Queue();
// Inserting elements in queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
// Printing front element
// using peek operation
q.peek();
}
}
JavaScript
// JS code for above operation
class Queue {
constructor() {
this.queue = [];
this.front = -1;
this.rear = -1;
this.capacity=10
}
enqueue(val) {
if (this.front == -1) {
this.front++;
}
if (this.rear == this.capacity-1) {
console.log("Queue overflow!!!");
}
this.queue[++(this.rear)] = val;
}
peek()
{
if (this.front == -1 || this.front > this.rear) {
console.log("Queue is empty !");
return;
}
console.log("Element at the front of queue: ",this.queue[this.front]);
}
};
let q = new Queue();
// Inserting elements in the queue
// using enqueue operation
q.enqueue(1);
q.enqueue(2);
q.peek();
// This code is contributed by adityamaharshi21
OutputElement at the front of queue: 1
Complexity Analysis:
- Time Complexity: O(1). In this operation, only a memory address is accessed. This is a constant time operation.
- Auxiliary Space: O(1). No extra space is utilized to access the first value.
Below is the implementation of peek() using Linked List:
C++
#include <iostream>
using namespace std;
#define capacity 10
class node {
public:
int data;
node* next;
node(int val)
{
data = val;
next = NULL;
}
};
class Queue {
public:
node* front;
node* rear;
Queue()
{
front = rear = NULL;
}
void enqueue(int val)
{
// if queue is empty
if (rear == NULL) {
// Create a new node as rear
rear = new node(val);
rear->next = NULL;
rear->data = val;
// Front will be rear as only
// one element exist in queue
front = rear;
}
else {
// Create temp node of val value
node* temp = new node(val);
// Add temp after the rear of queue
rear->next = temp;
// Update temp as the end element
rear = temp;
}
}
void peek()
{
// if queue is empty
if (front == NULL) {
cout << "Queue is empty!!!" << endl;
}
else {
// return value of front
cout << "Element present at the front of queue: " << front->data << "\n";
}
}
};
int main()
{
Queue q;
// Inserting elements using
// enqueue operation
q.enqueue(5);
q.enqueue(7);
// Front element using
// peek operation
q.peek();
return 0;
}
Java
import java.util.Scanner;
class Node {
int data;
Node next;
Node(int val)
{
data = val;
next = null;
}
}
class Queue {
Node front;
Node rear;
Queue() { front = rear = null; }
void enqueue(int val)
{
// if queue is empty
if (rear == null) {
// Create a new node as rear
rear = new Node(val);
rear.next = null;
rear.data = val;
// Front will be rear as only
// one element exist in queue
front = rear;
}
else {
// Create temp node of val value
Node temp = new Node(val);
// Add temp after the rear of queue
rear.next = temp;
// Update temp as the end element
rear = temp;
}
}
void peek()
{
// if queue is empty
if (front == null) {
System.out.println("Queue is empty!!!");
}
else {
// return value of front
System.out.println(
"Element present at the front of queue: "
+ front.data);
}
}
}
class Main {
public static void main(String[] args)
{
Queue q = new Queue();
// Inserting elements using
// enqueue operation
q.enqueue(5);
q.enqueue(7);
// Front element using
// peek operation
q.peek();
}
}
Python
class Node:
def __init__(self, val):
self.data = val
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self, val):
# if queue is empty
if self.rear is None:
# Create a new node as rear
self.rear = Node(val)
self.rear.next = None
self.rear.data = val
# Front will be rear as only
# one element exists in queue
self.front = self.rear
else:
# Create temp node of val value
temp = Node(val)
# Add temp after the rear of queue
self.rear.next = temp
# Update temp as the end element
self.rear = temp
def peek(self):
# if queue is empty
if self.front is None:
print("Queue is empty!!!")
else:
# return value of front
print("Element present at the front of queue:", self.front.data)
q = Queue()
# Inserting elements using
# enqueue operation
q.enqueue(5)
q.enqueue(7)
# Front element using
# peek operation
q.peek()
C#
//C# code for above approach
using System;
public class Node
{
public int data;
public Node next;
public Node(int val)
{
data = val;
next = null;
}
}
public class Queue
{
public Node front;
public Node rear;
public Queue()
{
front = null;
rear = null;
}
public void Enqueue(int val)
{
// if queue is empty
if (rear == null)
{
// Create a new node as rear
rear = new Node(val);
rear.next = null;
rear.data = val;
// Front will be rear as only
// one element exists in queue
front = rear;
}
else
{
// Create temp node of val value
Node temp = new Node(val);
// Add temp after the rear of queue
rear.next = temp;
// Update temp as the end element
rear = temp;
}
}
public void Peek()
{
// if queue is empty
if (front == null)
{
Console.WriteLine("Queue is empty!!!");
}
else
{
// return value of front
Console.WriteLine("Element present at the front of queue: " + front.data);
}
}
}
public class Program
{
public static void Main()
{
Queue q = new Queue();
// Inserting elements using
// Enqueue operation
q.Enqueue(5);
q.Enqueue(7);
// Front element using
// Peek operation
q.Peek();
}
}
//This code is contributed by shivamsharma215
JavaScript
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
class Queue {
constructor() {
this.front = this.rear = null;
}
enqueue(val) {
// if queue is empty
if (this.rear === null) {
// Create a new node as rear
this.rear = new Node(val);
this.rear.next = null;
this.rear.data = val;
// Front will be rear as only
// one element exist in queue
this.front = this.rear;
} else {
// Create temp node of val value
let temp = new Node(val);
// Add temp after the rear of queue
this.rear.next = temp;
// Update temp as the end element
this.rear = temp;
}
}
peek() {
// if queue is empty
if (this.front === null) {
console.log("Queue is empty!!!");
} else {
// return value of front
console.log(`Element present at the front of queue: ${this.front.data}`);
}
}
}
let q = new Queue();
// Inserting elements using
// enqueue operation
q.enqueue(5);
q.enqueue(7);
// Front element using
// peek operation
q.peek();
OutputElement present at the front of queue: 5
Complexity Analysis:
- Time Complexity: O(1). In linked list implementation also a single memory address is accessed. It takes constant time.
- Auxiliary Space: O(1). No extra space is utilized to access the first element.
4) initialize():
This operation takes an array and adds the element at the back of the Queue.
Implementation of initialize() using array:
C++
#include <iostream>
using namespace std;
#define capacity 10
class Queue {
public:
int queue[capacity];
int front;
int rear;
Queue()
{
front = -1;
rear = -1;
}
void enqueue(int val)
{
if (front == -1) {
front++;
}
if (rear == capacity - 1) {
cout << "Queue overflow !\n";
return;
}
queue[++rear] = val;
}
void initialize(int arr[], int N)
{
for (int i = 0; i < N; i++) {
// Value to be inserted
int val = arr[i];
// Inserting using enqueue
enqueue(val);
}
// Printing the queue
for (int i = front; i <= rear; i++) {
cout << queue[i] << " ";
}
}
};
// Driver code
int main()
{
Queue q;
int arr[] = { 2, 4, 7, 9, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
// Calling the initialize function
q.initialize(arr, N);
return 0;
}
Java
// Java code to perform initialization of queue
import java.io.*;
class GFG {
static final int capacity = 10;
static class Queue {
int queue[] = new int[capacity];
int front;
int rear;
void Queue()
{
front = -1;
rear = -1;
}
void enqueue(int val)
{
if (front == -1) {
front++;
}
if (rear == capacity - 1) {
System.out.println("Queue overflow!!!");
return;
}
queue[++rear] = val;
}
void initialize(int arr[], int N)
{
for (int i = 0; i < N; i++) {
// Value to be inserted
int val = arr[i];
// Inserting using enqueue
enqueue(val);
}
// Printing the queue
for (int i = front + 1; i <= rear; i++) {
System.out.println(queue[i] + " ");
}
}
}
public static void main(String[] args)
{
Queue q = new Queue();
int arr[] = { 2, 4, 7, 9, 1 };
int N = 5;
q.initialize(arr, N);
}
}
// This code is contributed by adityamaharshi21
Python3
# Python equivalent of the given code
class Queue:
def __init__(self):
# Front of the queue
self.front = -1
# Rear of the queue
self.rear = -1
# Queue array with a fixed capacity of 10
self.queue = [None] * 10
def enqueue(self, val):
# If the queue is empty, set front to 0
if self.front == -1:
self.front = 0
# If the rear is already at the end of the queue, return an overflow message
if self.rear == len(self.queue) - 1:
print("Queue overflow!")
return
# Increase the rear and add the value to the queue
self.rear += 1
self.queue[self.rear] = val
def initialize(self, arr):
for val in arr:
# Insert each value in the array into the queue
self.enqueue(val)
# Print the queue
for i in range(self.front, self.rear + 1):
print(self.queue[i], end=" ")
if __name__ == "__main__":
# Create a new queue object
q = Queue()
# Array to be inserted into the queue
arr = [2, 4, 7, 9, 1]
# Initialize the queue with the array
q.initialize(arr)
# This code is contributed by Vikram_Shirsat
C#
// C# code to initialize a queue
using System;
public class GFG {
public const int capacity = 10;
class Queue {
public int[] queue = new int[GFG.capacity];
public int front;
public int rear;
public Queue()
{
this.front = -1;
this.rear = -1;
}
public void enqueue(int val)
{
if (this.front == -1) {
this.front++;
}
if (this.rear == GFG.capacity - 1) {
Console.WriteLine("Queue overflow!!!");
return;
}
this.queue[++this.rear] = val;
}
public void initialize(int[] arr, int N)
{
for (int i = 0; i < N; i++) {
// Value to be inserted
int val = arr[i];
// Inserting using enqueue
enqueue(val);
}
for (int i = this.front; i <= this.rear; i++) {
Console.WriteLine(queue[i] + " ");
}
}
}
public static void Main(String[] args)
{
var q = new Queue();
// Inserting elements in queue
// using enqueue operation
int[] arr = { 2, 4, 7, 9, 1 };
int N = 5;
q.initialize(arr, N);
}
}
// This code is contributed by adityamaharshi21.
JavaScript
// JS code for above operation
class Queue {
constructor() {
this.queue = [];
this.front = -1;
this.rear = -1;
this.capacity = 10;
}
enqueue(val) {
if (this.front == -1) {
this.front++;
}
if (this.rear == this.capacity) {
console.log("Queue overflow!!!");
}
this.queue[this.rear=this.rear+1] = val;
}
initialize(arr, N) {
for (let i = 0; i < N; i++) {
// Value to be inserted
let val = arr[i];
// Inserting using enqueue
this.enqueue(val);
}
// Printing the queue
for (let i = 0; i <= 4; i++) {
console.log(this.queue[i]);
}
}
};
// Driver code
let q = new Queue();
let arr = [2, 4, 7, 9, 1];
let N = arr.length;
// Calling the initialize function
q.initialize(arr, N);
// This code is contributed by adityamaharshi21
Complexity Analysis:
- Time Complexity: O(N). Inserting each element is a constant time operation. So for inserting N elements N unit of time is required.
- Auxiliary Space: O(N). N elements are inserted.
Implementation of initialize() using LinkedList:
C++
#include <iostream>
using namespace std;
class node {
public:
int data;
node* next;
node(int val)
{
data = val;
next = NULL;
}
};
class Queue {
public:
node* front;
node* rear;
Queue()
{
front = rear = NULL;
}
void enqueue(int val)
{
// if queue is empty
if (rear == NULL) {
// Create a new node as rear
rear = new node(val);
rear->next = NULL;
rear->data = val;
// Front will be rear as only
// one element exist in queue
front = rear;
}
else {
// Create temp node of val value
node* temp = new node(val);
// Add temp after the rear of queue
rear->next = temp;
// Update temp as the end element
rear = temp;
}
}
void initialize(int arr[], int N)
{
for (int i = 0; i < N; i++) {
// Value to be inserted
int val = arr[i];
// Inserting using enqueue
enqueue(val);
}
node* temp = front;
// Printing the queue
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
}
};
// Driver code
int main()
{
Queue q;
int arr[] = { 2, 8, 7, 3, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
// Calling the initialize function
q.initialize(arr, N);
return 0;
}
Java
class Node {
public int data;
public Node next;
public Node(int val) {
data = val;
next = null;
}
}
class Queue {
public Node front;
public Node rear;
public Queue() {
front = rear = null;
}
public void enqueue(int val) {
// if queue is empty
if (rear == null) {
// Create a new node as rear
rear = new Node(val);
rear.next = null;
rear.data = val;
// Front will be rear as only
// one element exist in queue
front = rear;
} else {
// Create temp node of val value
Node temp = new Node(val);
// Add temp after the rear of queue
rear.next = temp;
// Update temp as the end element
rear = temp;
}
}
public void initialize(int[] arr, int N) {
for (int i = 0; i < N; i++) {
// Value to be inserted
int val = arr[i];
// Inserting using enqueue
enqueue(val);
}
Node temp = front;
// Printing the queue
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
}
// Driver code
public class Main {
public static void main(String[] args) {
Queue q = new Queue();
int[] arr = {2, 8, 7, 3, 1};
int N = arr.length;
// Calling the initialize function
q.initialize(arr, N);
}
}
Python3
# Python equivalent of the C++ code
# Define the node class
class Node:
def __init__(self, val):
self.data = val
self.next = None
# Define the Queue class
class Queue:
def __init__(self):
self.front = self.rear = None
def enqueue(self, val):
# If queue is empty
if self.rear is None:
# Create a new node as rear
self.rear = Node(val)
self.rear.next = None
self.rear.data = val
# Front will be rear as only one element exist in queue
self.front = self.rear
else:
# Create temp node of val value
temp = Node(val)
# Add temp after the rear of queue
self.rear.next = temp
# Update temp as the end element
self.rear = temp
def initialize(self, arr, N):
for i in range(N):
# Value to be inserted
val = arr[i]
# Inserting using enqueue
self.enqueue(val)
temp = self.front
# Printing the queue
while temp is not None:
print(temp.data, end=' ')
temp = temp.next
# Driver code
if __name__ == '__main__':
q = Queue()
arr = [2, 8, 7, 3, 1]
N = len(arr)
# Calling the initialize function
q.initialize(arr, N)
# This code is contributed by Vikram_Shirsat
C#
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
// C# ptogram for the above approach
// Define the node class
class Node {
public int data;
public Node next;
public Node(int val) {
data = val;
next = null;
}
}
// Define the Queue class
class queue {
public Node front;
public Node rear;
public queue() {
front = null;
rear = null;
}
public void enqueue(int val) {
// If queue is empty
if (rear == null) {
// Create a new node as rear
rear = new Node(val);
rear.next = null;
rear.data = val;
// Front will be rear as only one element exists in queue
front = this.rear;
} else {
// Create temp node of val value
Node temp = new Node(val);
// Add temp after the rear of queue
rear.next = temp;
// Update temp as the end element
rear = temp;
}
}
public void initialize(int[] arr,int N) {
for (int i = 0; i < N; i++) {
// Value to be inserted
int val = arr[i];
// Inserting using enqueue
enqueue(val);
}
Node temp = front;
// Printing the queue
List<int> ans = new List<int>();
while (temp != null) {
ans.Add(temp.data);
temp = temp.next;
}
for(int i = 0; i < ans.Count; i++){
Console.Write(ans[i] + " ");
}
}
}
class HelloWorld {
static void Main() {
// Driver code
queue q= new queue();
int[] arr = {2, 8, 7, 3, 1};
int N = arr.Length;
// Calling the initialize function
q.initialize(arr, N);
}
}
// The code is contributed by Arushi Jindal.
JavaScript
// Javascript program for the above approach
// Define the node class
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
// Define the Queue class
class Queue {
constructor() {
this.front = null;
this.rear = null;
}
enqueue(val) {
// If queue is empty
if (this.rear === null) {
// Create a new node as rear
this.rear = new Node(val);
this.rear.next = null;
this.rear.data = val;
// Front will be rear as only one element exists in queue
this.front = this.rear;
} else {
// Create temp node of val value
let temp = new Node(val);
// Add temp after the rear of queue
this.rear.next = temp;
// Update temp as the end element
this.rear = temp;
}
}
initialize(arr, N) {
for (let i = 0; i < N; i++) {
// Value to be inserted
let val = arr[i];
// Inserting using enqueue
this.enqueue(val);
}
let temp = this.front;
// Printing the queue
let ans = []
while (temp !== null) {
ans.push(temp.data);
temp = temp.next;
}
console.log(ans.join(" "));
}
}
// Driver code
let q = new Queue();
let arr = [2, 8, 7, 3, 1];
let N = arr.length;
// Calling the initialize function
q.initialize(arr, N);
// This code is contributed by codebraxnzt
Complexity Analysis:
- Time Complexity: O(N). Creating a new node and making a link takes unit time. So to insert N elements (i.e., creating N nodes and linking them) N unit of times is required.
- Auxiliary Space: O(N). N elements need to be inserted.
5) isfull():
Function that returns true if the queue is filled completely else returns false.
Below is the implementation of isfull() using array:
C++
#include <iostream>
using namespace std;
#define capacity 10
class Queue {
public:
int queue[capacity];
int front;
int rear;
Queue()
{
front = -1;
rear = -1;
}
bool isfull()
{
if (rear == capacity - 1)
return 1;
return 0;
}
};
int main()
{
Queue q;
if (q.isfull()) {
cout << "Queue is filled\n";
}
else {
cout << "Queue is not filled completely\n";
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
static class Queue {
int capacity = 10;
int queue[];
int front;
int rear;
Queue()
{
front = -1;
rear = -1;
queue = new int[capacity];
}
boolean isfull()
{
if (rear == capacity - 1)
return true;
return false;
}
}
public static void main(String[] args)
{
Queue q = new Queue();
if (q.isfull()) {
System.out.println("Queue is filled\n");
}
else {
System.out.println(
"Queue is not filled completely\n");
}
}
}
// This code is contributed by aadityaburujwale.
Python3
# Python equivalent of the code
# Define the Queue class
class Queue:
capacity = 10
def __init__(self):
self.front = -1
self.rear = -1
def isfull(self):
if self.rear == self.capacity - 1:
return True
return False
# Driver code
if __name__ == '__main__':
q = Queue()
if q.isfull():
print("Queue is filled")
else:
print("Queue is not filled completely")
# This code is contributed by Vikram_Shirsat
C#
// C# code addition
using System;
class Queue
{
public const int capacity = 10;
public int[] queue = new int[capacity];
public int front = -1;
public int rear = -1;
public bool IsFull()
{
if (rear == capacity - 1)
return true;
return false;
}
}
class Program
{
static void Main(string[] args)
{
Queue q = new Queue();
if (q.IsFull())
{
Console.WriteLine("Queue is filled");
}
else
{
Console.WriteLine("Queue is not filled completely");
}
}
}
// The code is contributed by Arushi Goel.
JavaScript
class Queue {
constructor() {
this.queue = [];
this.front = -1;
this.rear = -1;
this.capacity=10
}
isfull()
{
if (this.rear == this.capacity - 1)
return true;
return false;
}
};
let q = new Queue();
if (q.isfull()) {
console.log("Queue is filled\n");
}
else {
console.log("Queue is not filled completely\n");
}
// This code is contributed by akashish__.
OutputQueue is not filled completely
Complexity Analysis:
- Time Complexity: O(1). It only performs an arithmetic operation to check if the queue is full or not.
- Auxiliary Space: O(1). It requires no extra space.
Below is the implementation of isfull() using Linked List:
C++
#include <iostream>
using namespace std;
#define capacity 10
class node {
public:
int data;
node* next;
node(int val)
{
data = val;
next = NULL;
}
};
class Queue {
public:
node* front;
node* rear;
Queue()
{
front = rear = NULL;
}
bool isfull()
{
// to store current length of queue
int length = 0;
// temp pointing to front node
node* temp = front;
// if queue is empty
if (temp == NULL)
return 0;
while (temp->next != NULL) {
length++;
temp = temp->next;
}
// if queue size is same as maximum capacity
if (length == capacity) {
return 1;
}
return 0;
}
};
int main()
{
Queue q;
if (q.isfull()) {
cout << "Queue is filled\n";
}
else {
cout << "Queue is not filled completely\n";
}
return 0;
}
Java
import java.util.*;
class Node {
public int data;
public Node next;
public Node(int val) {
data = val;
next = null;
}
}
class Queue {
public Node front;
public Node rear;
public static final int capacity = 10; // Add this line
public Queue() {
front = rear = null;
}
public boolean isFull() {
// to store current length of queue
int length = 0;
// temp pointing to front node
Node temp = front;
// if queue is empty
if (temp == null)
return false;
while (temp.next != null) {
length++;
temp = temp.next;
}
// if queue size is same as maximum capacity
return length == capacity;
}
}
public class Main {
public static void main(String[] args) {
Queue q = new Queue();
if (q.isFull()) {
System.out.println("Queue is filled");
} else {
System.out.println("Queue is not filled completely");
}
}
}
Python3
# Python equivalent of the C++ code
# Define the node class
class node:
def __init__(self, val):
self.data = val
self.next = None
# Define the Queue class
class Queue:
capacity = 10
def __init__(self):
self.front = None
self.rear = None
def isfull(self):
length = 0
temp = self.front
if temp is None:
return False
while temp.next is not None:
length += 1
temp = temp.next
if length == self.capacity:
return True
return False
# Driver code
if __name__ == '__main__':
q = Queue()
if q.isfull():
print("Queue is filled")
else:
print("Queue is not filled completely")
# This code is contributed by Vikram_Shirsat
C#
using System;
public class Node
{
public int Data { get; set; }
public Node Next { get; set; }
public Node(int val)
{
Data = val;
Next = null;
}
}
public class Queue
{
public Node Front { get; set; }
public Node Rear { get; set; }
public Queue()
{
Front = Rear = null;
}
public bool IsFull()
{
// to store the current length of the queue
int length = 0;
// temp pointing to the front node
Node temp = Front;
// if the queue is empty
if (temp == null)
return false;
while (temp.Next != null)
{
length++;
temp = temp.Next;
}
// if the queue size is the same as the maximum capacity
if (length == Program.capacity)
{
return true;
}
return false;
}
}
class Program
{
public static int capacity = 10;
static void Main()
{
Queue q = new Queue();
if (q.IsFull())
{
Console.WriteLine("Queue is filled");
}
else
{
Console.WriteLine("Queue is not filled completely");
}
}
}
JavaScript
// JS code for above operation
class Queue {
constructor() {
this.queue = [];
this.front = -1;
this.rear = -1;
this.capacity = 10
}
isfull() {
if (this.rear == this.capacity - 1)
return 1;
return 0;
}
};
let q = new Queue();
if (q.isfull()) {
console.log("Queue is filled");
}
else {
console.log("Queue is not filled completely");
}
// This code is contributed by adityamaharshi21
OutputQueue is not filled completely
Complexity Analysis:
- Time Complexity: O(N). The whole linked list is traversed to calculate the length and then the length is checked with the capacity. The traversal of the linked list takes O(N) time.
- Auxiliary Space: O(1). No extra space is required.
6) isempty():
Function that returns true if the queue is empty else returns false.
Below is the implementation of isempty() operation using array:
C++
#include <iostream>
using namespace std;
#define capacity 10
class Queue {
public:
int queue[capacity];
int front;
int rear;
Queue()
{
front = -1;
rear = -1;
}
bool isempty()
{
// if there are no elements or
// the queue has exceed its rear
if (front == -1 || front > rear) {
return 1;
}
return 0;
}
};
int main()
{
Queue q;
if (q.isempty()) {
cout << "Queue is empty\n";
}
else {
cout << "Queue is not empty \n";
}
return 0;
}
Java
public class Queue {
private static final int capacity = 10;
private int[] queue;
private int front;
private int rear;
public Queue() {
queue = new int[capacity];
front = -1;
rear = -1;
}
public boolean isEmpty() {
// if there are no elements or
// the queue has exceeded its rear
if (front == -1 || front > rear) {
return true;
}
return false;
}
public static void main(String[] args) {
Queue q = new Queue();
if (q.isEmpty()) {
System.out.println("Queue is empty");
} else {
System.out.println("Queue is not empty");
}
}
}
Python3
# Check if a queue is empty or not
class Queue:
def __init__(self):
self.queue = []
self.front = -1
self.rear = -1
def isempty(self):
if self.front == -1 or self.front > self.rear:
return True
return False
q = Queue()
if q.isempty():
print("Queue is empty")
else:
print("Queue is not empty")
# This code is contributed by Vikram_Shirsat
C#
using System;
class Queue
{
private const int Capacity = 10;
private int front;
private int rear;
public Queue()
{
front = -1;
rear = -1;
}
public bool IsEmpty()
{
// If there are no elements or the queue has exceeded its rear
if (front == -1 || front > rear)
{
return true;
}
return false;
}
}
class Program
{
static void Main()
{
Queue q = new Queue();
if (q.IsEmpty())
{
Console.WriteLine("Queue is empty");
}
else
{
Console.WriteLine("Queue is not empty");
}
}
}
JavaScript
//JS code for above approach
class Queue {
constructor() {
this.queue = [];
this.front = -1;
this.rear = -1;
this.capacity = 10;
}
isempty() {
// if there are no elements or
// the queue has exceed its rear
if (this.front == -1 || this.front > this.rear) {
return 1;
}
return 0;
}
};
// Driver Code
let q = new Queue;
if (q.isempty()) {
console.log("Queue is empty");
}
else {
console.log("Queue is not empty ");
}
// This code is contributed by adityamaharshi21
Complexity Analysis:
- Time Complexity: O(1) It only checks the position stored in the first and last pointer
- Auxiliary Space: O(1) NO extra space is required to check the values of the first and the last pointer.
Below is the implementation of isempty() operation using LinkedList:
C++
#include <iostream>
using namespace std;
#define capacity 10
class node {
public:
int data;
node* next;
node(int val)
{
data = val;
next = NULL;
}
};
class Queue {
public:
node* front;
node* rear;
Queue()
{
front = rear = NULL;
}
bool isempty()
{
// if queue has 0 nodes
if (front == NULL) {
return 1;
}
return 0;
}
};
int main()
{
Queue q;
if (q.isempty()) {
cout << "Queue is filled\n";
}
else {
cout << "Queue is not filled completely\n";
}
return 0;
}
Java
class Node {
public int data;
public Node next;
public Node(int val) {
data = val;
next = null;
}
}
class Queue {
public Node front;
public Node rear;
public Queue() {
front = rear = null;
}
public boolean isEmpty() {
// if the queue has 0 nodes
if (front == null) {
return true;
}
return false;
}
}
public class Main {
public static void main(String[] args) {
Queue q = new Queue();
if (q.isEmpty()) {
System.out.println("Queue is filled");
} else {
System.out.println("Queue is not filled completely");
}
}
}
Python3
# Python program for the above approach
class Node:
def __init__(self, val):
self.data = val
self.next = None
class Queue:
def __init__(self):
self.front = self.rear = None
def isempty(self):
if self.front == None:
return True
return False
if __name__ == '__main__':
q = Queue()
if q.isempty():
print("Queue is filled")
else:
print("Queue is not filled completely")
# This code is contributed by adityashatmfh
C#
using System;
// Node class represents a node in the linked list
public class Node
{
public int Data;
public Node Next;
// Constructor to initialize a node with given value
public Node(int val)
{
Data = val;
Next = null;
}
}
// Queue class represents a basic queue using linked list
public class Queue
{
public Node Front; // Front points to the first node in the queue
public Node Rear; // Rear points to the last node in the queue
// Constructor to initialize an empty queue
public Queue()
{
Front = Rear = null;
}
// Method to check if the queue is empty
public bool IsEmpty()
{
// If Front is null, the queue has 0 nodes
if (Front == null)
{
return true;
}
return false;
}
}
class Program
{
static void Main()
{
Queue q = new Queue();
// Check if the queue is empty and print the result
if (q.IsEmpty())
{
Console.WriteLine("Queue is filled");
}
else
{
Console.WriteLine("Queue is not filled completely");
}
}
}
JavaScript
// JavaScript Program for the above approach
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
class Queue {
constructor() {
this.front = null;
this.rear = null;
}
isempty() {
if (this.front == null) {
return true;
}
return false;
}
}
let q = new Queue();
if (q.isempty()) {
console.log("Queue is filled");
} else {
console.log("Queue is not filled completely");
}
// This code is contributed by codebraxnzt
Complexity Analysis:
- Time Complexity: O(1), It checks if the pointer of first is Null or not. This operation takes constant time.
- Auxiliary Space: O(1). No extra space is required.
Similar Reads
Time and Space Complexity analysis of Stack operations
What is Stack?Stack is a linear data structure that follows a particular order in which the elements are inserted and deleted. A stack follows the principle of last in first out(LIFO) which means that the last element inserted into the stack should be removed first. Consider an example of plates sta
15+ min read
Time and Space complexity analysis of Selection Sort
The Selection sort algorithm has a time complexity of O(n^2) and a space complexity of O(1) since it does not require any additional memory space apart from a temporary variable used for swapping. Time Complexity Analysis of Selection Sort:Best-case: O(n2), best case occurs when the array is already
2 min read
Time and Space Complexity Analysis of Merge Sort
The Time Complexity of Merge Sort is O(n log n) in both the average and worst cases. The space complexity of Merge sort is O(n). AspectComplexityTime ComplexityO(n log n)Space ComplexityO(n)Time Complexity Analysis of Merge Sort:Consider the following terminologies: T(k) = time taken to sort k eleme
2 min read
Time and Space Complexity Analysis of Prim's Algorithm
The time complexity of Prim's algorithm is O(V2) using an adjacency matrix and O((V +E) log V) using an adjacency list, where V is the number of vertices and E is the number of edges in the graph. The space complexity is O(V+E) for the priority queue and O(V2) for the adjacency matrix representation
3 min read
Time and Space complexity of 1-D and 2-D Array Operations
The time and space complexity of one-dimensional and two-dimensional array operations can vary depending on the specific operation. Here, we'll discuss common array operations and provide insights into their time and space complexities for one-dimensional and two-dimensional arrays. One-Dimensional
3 min read
Practice Questions on Time Complexity Analysis
Prerequisite: Analysis of Algorithms1. What is the time, and space complexity of the following code: CPPint a = 0, b = 0; for (i = 0; i < N; i++) { a = a + rand(); } for (j = 0; j < M; j++) { b = b + rand(); } Javaint a = 0, b = 0; for (i = 0; i < N; i++) { a = a + Math.random(); } for (j =
7 min read
Time and Space complexity of Radix Sort Algorithm
The Radix Sort Algorithm has a time complexity of O(n*d), where n is the number of elements in the input array and d is the number of digits in the largest number. The space complexity of Radix Sort is O(n + k), where n is the number of elements in the input array and k is the range of the input. Th
2 min read
Time and Space Complexity Analysis of Kruskal Algorithm
Kruskal's algorithm is a popular algorithm for finding the Minimum Spanning Tree (MST) of a connected, undirected graph. The time complexity of Kruskal's algorithm is O(E log E), where E is the number of edges in the graph. The space complexity of Kruskal's algorithm is O(V + E), where V is the numb
2 min read
Step Count Method for Time Complexity Analysis
What is Time Complexity? Time Complexity is the amount of time taken by the algorithm to run. It measures the time taken to execute each statement of code in an algorithm. Time Complexity can be calculated by using Two types of methods. They are: Step Count MethodAsymptotic Notation. Here, we will d
4 min read
Time and Space Complexity of Insertion Sort
What is Insertion Sort?Insertion sort is a simple sorting algorithm that works similarly to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed in the correct position in the sorted part. T
2 min read