0% found this document useful (0 votes)
29 views25 pages

Queue Operations and Checks

The document contains code for implementing various queue operations like enqueue, dequeue, display using arrays as well as linked lists. It also contains code to count even and odd elements in a queue, reverse the first m elements of a queue where m is less than the total size n, and reverse the entire queue. Methods are defined to check if the queue is full or empty, insert and remove elements, display the queue. Main method is used to test the queue operations by taking user input for size and elements.

Uploaded by

sakshi goyal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views25 pages

Queue Operations and Checks

The document contains code for implementing various queue operations like enqueue, dequeue, display using arrays as well as linked lists. It also contains code to count even and odd elements in a queue, reverse the first m elements of a queue where m is less than the total size n, and reverse the entire queue. Methods are defined to check if the queue is full or empty, insert and remove elements, display the queue. Main method is used to test the queue operations by taking user input for size and elements.

Uploaded by

sakshi goyal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Sakshi 19csu269

Queue Assignment
Ques-1)
Ans) import [Link].*;
public class ReverseArray2{
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;

void Queue() {
front = -1;
rear = -1;
}

// check if the queue is full


boolean isFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}

// check if the queue is empty


boolean isEmpty() {
if (front == -1)
return true;
else
return false;
}

// insert elements to the queue


void enQueue(int element) {

// if queue is full
if (isFull()) {
[Link]("Queue is full");
}
else {
if (front == -1) {
// mark front denote first element of queue
front = 0;
}

rear++;
// insert element at the rear
items[rear] = element;
[Link]("Insert " + element);
}
}
// delete element from the queue
int deQueue() {
int element;

// if queue is empty
if (isEmpty()) {
[Link]("Queue is empty");
return (-1);
}
else {
// remove element from the front of queue
element = items[front];

// if the queue has only one element


if (front >= rear) {
front = -1;
rear = -1;
}
else {
// mark next element as the front
front++;
}
[Link]( element + " Deleted");
return (element);
}
}
// display element of the queue
void display() {
int i;
if (isEmpty()) {
[Link]("Empty Queue");
}
else {
[Link]("\nFront-> " + front);

[Link]("Items -> ");


for (i = front; i <= rear; i++)
[Link](items[i] + " ");

[Link]("\nRear index-> " + rear);


}
}
void reversequeue()
{
int temp=0;
int s=SIZE/2;
for(int i=front,j=rear;i<s&&j>s;i++,j--)
{
temp=items[i];
items[i]=items[j];
items[j]=temp;

}
[Link]("Queue after Reverse=");
for (int i = front; i < rear+1; i++) {
[Link](items[i]);
}
}

public static void main(String[] args) {

ReverseArray2 q = new ReverseArray2();


q .Queue();

q. deQueue();

[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);
[Link]();
[Link]();

}
}

Screenshot

Ques-2)
Ans) class Node
{
int data; // integer data
Node next; // pointer to the next node

public Node(int data)


{
// set the data in allocated node and return the node
[Link] = data;
[Link] = null;
}
}
class Queue
{
private static Node rear = null, front = null;

// Utility function to remove front element from the queue


public static int dequeue() // delete at the beginning
{
if (front == null) {
[Link]("\nQueue Underflow");
[Link](1);
}

Node temp = front;


[Link]("Removing %d\n", [Link]);

// advance front to the next node


front = [Link];

// if list becomes empty


if (front == null) {
rear = null;
}
// deallocate the memory of removed node and
// optionally return the removed item
int item = [Link];
return item;
}

// function to add an item in the queue


public static void enqueue(int item)
{

Node node = new Node(item);


[Link]("Inserting %d\n", item);

// queue was empty


if (front == null) {
// initialize both front and rear
front = node;
rear = node;
} else {
// update rear
[Link] = node;
rear = node;
}
}

// Utility function to return top element in a queue


public static int display() {
// check for empty queue
if (front != null) {
return [Link];
} else {
[Link](1);
}

return -1;
}

// Utility function to check if the queue is empty or not


public static boolean isEmpty() {
return rear == null && front == null;
}
}

void reversequeue(int size)


{
Queue temp=front;
Queue ptr1=rear;
//front=rear;
for(int i=0;i<size;i++)
{
while([Link]!=rear)
{
temp=[Link];
}
[Link]=temp;
rear=temp;
}
[Link]=null;
front=ptr1;
}
class Main
{
public static void main(String[] args)
{ size=3;
Queue q = new Queue();
[Link](1);
[Link](2);
[Link](3);
[Link](4);

[Link]("Front element is %d\n", [Link]());

[Link](size);
[Link]();

if ([Link]()) {
[Link]("Queue is empty");
} else {
[Link]("Queue is not empty");
}
}
}

Screenshot

Ques-3)
Ans) import [Link].*;
class Queue
{
int front=-1;
int rear=-1;
int[] arr=new int[10];

void insert(int data)


{
if(rear==([Link]-1))
{
[Link]("Stack overflow");
return;
}

if(front==-1 && rear==-1)


{
front=rear=0;
arr[rear]=data;
}
else
{
rear=rear+1;
arr[rear]=data;
}

void remove()
{
if(front==-1||front>rear)
{
[Link]("Stack is empty");
}
else
{
front=front+1;
}
}

void display()
{
for(int i=front;i<=rear;i++)
{
[Link](arr[i]);
}
}

void count()
{
int count=0;
for(int temp=front;temp<=rear;temp++)
{
if(arr[temp]%2==0)
{
count++;
}
}
[Link](count);
}
}
class Scountqueue
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
Queue m=new Queue();
int choice;
char ch='y';
while(ch=='y')
{
[Link]("[Link] an element");
[Link]("[Link] an element");
[Link]("[Link] the queue");

[Link]("Enter the choice");


choice=[Link]();

switch(choice)
{
case 1:[Link]("enter data to insert");
int data;
data=[Link]();
[Link](data);
break;

case 2:[Link]();
break;

case 3: [Link]();
break;
}
[Link]("want to continue?");
ch=[Link]().charAt(0);

}
[Link]();

}
}

Screenshot
Ques-4)
Ans) // Write a program to count the odd numbers in a queue using linked list
import [Link].*;
class Queue
{
static Queue front;
static Queue rear;
Queue next;
int data;

public Queue()
{
[Link]=null;
}
public Queue(int data)
{
[Link]=data;
[Link]=null;
}
public Queue(int data,Queue next)
{
[Link]=data;
[Link]=next;
}

public void enqueue(int data) // function to add elements


{
Queue temp;
temp=new Queue(data); // creting a new node temp
if(rear==null)
{
rear=front=temp; // inserting the first element
}
else
{
[Link]=temp;
[Link]=null;
rear=temp; // updating the last node after insertion
}
}
public void dequeue() // function to delete elements
{
if(front==null) // if the queue is empty
{
[Link]("Queue is empty");
}
else
{
front=[Link]; // updating the front after deletion
}
}
public void display() // function to print the queue
{
Queue temp;
if(front==null)
{
[Link]("Queue is empty");
}
else
{
temp=front; // initializing temp
while(temp!=rear)
{
[Link]([Link]+" ");
temp=[Link]; // prints data till 2nd last node
}
[Link]([Link]); // printing the last node
}
}
public int count_odd()
{
int count=0;
Queue temp=front;
for(;temp!=rear;temp=[Link])
{
if([Link]%2!=0)
count++;
}
if([Link]%2!=0)
count++;
return count;
}
}
public class odd extends Queue
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
Queue qu=new Queue();
int i,size,data,del_size;
[Link]("Enter the size of the queue");
size=[Link]();
[Link]("------------------");
if(size!=0)
{
[Link]("Enter the elements");
}
for(i=1;i<=size;i++)
{
data=[Link]();
[Link](data);
}
if(front!=null)
{
[Link]("Elements of the queue are");
}
[Link]();
[Link]("No. of odd elements in the queue is:"+qu.count_odd());
}
}

Screenshot
Ques-5)
Ans) // Write a program to reverse the first m elements from the queue, where m < n, n is
the total number of elements in queue.
import [Link];

public class Queuer {

public static int front, rear, max; //front use as deleting end and rear use as inserting end
and max is mx size of queue
public static int queue[]; //array of type int

Queuer(int m) //constructor of class queue and parameter use is the max. size of queue
{
front = rear = -1;
max = m;
queue = new int[max];
}

public static void Enqueue(int data)


{ //function enqueue to insert value in queue

if (rear== max-1) //condtion to check whether the queue is full or not


{
[Link]("Queue is full");
return;
}
if(front == -1 & rear ==-1)
{
front=rear=0;
queue[rear]=data;
}

else {rear++; //if queue is not reach to max. size of it then value added in queue
queue[rear] = data;

}
return;
} //end of function
public static void rev(int s)
{
int temp=0;

for(int i=0,j=s-1;i<s/2&&j>s/2;i++,j--)
{
temp=queue[i];
queue[i]=queue[j];
queue[j]=temp;

}[Link]("queue after reverse");


queueDisplay();
}
public static void queueDisplay()//function display value to display each value of queue
{
int i;
if (front == -1 & rear ==-1) { //condtion to check whether queue is empty or not
[Link]("Queue is Empty");
return;
}

for (i = front; i < rear+1; i++) { //if queue is not empty then display all value present in
queue
[Link](queue[i]);
}
return;
} //end of function
public static void main(String[] args)
{
Scanner sc=new Scanner([Link]); //creating a object of scanner class
Queuer q = new Queuer(5); //creating a object of queue class and calling constructor
of queue class
int data;
[Link]("Enter the number of element u want to add in queue");
int size=[Link]();
for(int i=0;i<size;i++)
{
[Link]("Enter a value u want to add: ");
data=[Link]();
Enqueue(data); //calling a function enqueue
}
[Link]("queue before reverse");
queueDisplay();
int m;
[Link]("enter the from which u want to reverse:");
m=[Link]();
rev(m);

Screenshot

Common questions

Powered by AI

In Source 1, the reverse method swaps elements in place using a temporary variable and iterates from both ends towards the center using indices. The method halves the total queue elements by SIZE/2 for iterations, which assumes an Array implementation. In contrast, Source 2 uses nodes (linked list), iteratively redirects the pointers of nodes starting from the rear, with a temporary and pointer adjustment to reverse the links within the queue; this approach accommodates node distinction without specific position calculations.

In Source 1, a queue is empty if 'front == -1', which indicates no elements are actively allocated within the array space. In contrast, Source 3 checks if 'front == -1 || front > rear', combining an initial empty condition similar to Source 1 with an additional safeguard to assert no remaining elements between front and rear in a sequential array. This subtly highlights reliance on index values directly hinting at queue state.

Queue underflow in array-based methods (seen in Source 1) is managed by checking if 'front == -1', meaning an immediate termination of operations when attempting dequeue. Node-based methods emphasize checking 'if (front == null)' as underflow, with a graceful error output before ceasing program execution (exit). Array methods focus on preventing out-of-bound execution, while node-based handling centers on pointer availability, hinting at differing methodology dictated by structure limitations.

The circular queue in Source 1, using array indexing, effectively utilizes space by allowing wrap-around, making use of all allocated space when front or rear surpasses the array length. This increases efficient memory utilization. Conversely, Source 2's linear queue using linked lists inherently provides dynamic resizing capabilities without predetermined size limits, offering more flexibility at the cost of additional overhead for managing node pointers.

Source 2 employs node-based insertion for enqueue where a new node is dynamically created and linked to the rear, allowing efficient, unlimited growth of the queue. Source 3 uses typical array indices to adjust rear pointers, building the array-based structure with fixed maximum size. The key difference lies in the dynamic nature favoring flexibility in Source 2 versus the static but straightforward approach in Source 3.

The main loop in Source 4 utilizes an analytical cognitive process focused on evaluating each queue element individually to determine specific characteristics—in this case, whether the number is odd. The loop iterates through nodes, analyzing node data with conditional checks (oddness), which enables detailed and specific data aggregation based on the processed elements, representing detailed exploration of data attributes within the data structure.

In Source 1, a queue overflow is signaled when both 'front == 0' and 'rear == SIZE-1'. This condition denotes a full array, preventing further enQueue operations. Overflow, in this structure, immediately halts insertion attempts and signals to user space limitations. Programmatically, it enforces tighter data management policies or the need for alternate strategies such as dynamic resizing or alternate data structure selection.

The counting method in Source 3 is used to iterate through elements systematically, especially given its dynamic nature with linked lists, counting helps segregate specific elements like odd numbers or prepare elements en masse for operations such as resetting or reversing. This systematic approach simplifies managing pointer structures across list changes.

Using an array for a queue, as shown in several sources, benefits include simplicity of implementation and straightforward indexing for queue operations. It also offers constant-time complexity for most insertion and deletion operations, assuming the array organization accommodates wraparounds. However, drawbacks include fixed size, leading to potential space inefficiency if not fully utilized, along with the complexity involved in resizing when full, versus the inherent dynamic resizing of linked lists.

Dedicated display methods, as employed repeatedly across sources, emphasize principles of modularity and single-responsibility. By isolating queue display features, separation of concerns is achieved, facilitating maintenance and clarity. It supports broader software design philosophies where individual methods drive specific task specialization, limit cross-interaction complexity, and ease testing and debugging through clear input/output delineations. This aligns with systemic engineering frameworks advocating for isolated functionality.

You might also like