0% found this document useful (0 votes)
18 views94 pages

Dsa Record-2022 - Batch - CS

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)
18 views94 pages

Dsa Record-2022 - Batch - CS

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
You are on page 1/ 94

RVS COLLEGE OF ARTS AND SCIENCE

Name :

Register Number :

Class :

Subject :
RVS COLLEGE OF ARTS AND SCIENCE

Sulur, Coimbatore – 641 402

REGISTER NUMBER

Certified that this is a bonafide record of............................................................................

..........................................................................................................practical work
doneby

Mr./Ms pursuing

.............................................. in I / II / III / IV / V / VI semester

during the academicyear2023-2024.

Faculty HoD

Submitted for the Practical Examination held at RVS College


of Arts and Science on................
Examiners:

Internal…………………………..….

External………………….……….…
o
EX. NO: 1 FACTORIAL OF N NUMBERS USING RECURSION DATE :

Aim:
To Develop a Java function to perform a Factorial of N numbers using Recursion and
specify its Time Complexity.

TASK 1: Creating the Class “factorialRecursion”


● Import the util package
● Create a class named ”factorialRecursion”.

TASK 2: Creating the Main Function

● Using the “scanner class” object “in” get the input for finding the Factorial.
● Assign the input received from the input source to an integer variable “n”.
● Check whether the input is a positive integer
● If the value of “n<0”, print as “Invalid number”.
● Else invoke “Factorial Function”
ALGORITHM:

Implement the factorial Recursive Function.


STEP 1: Include the parameter “n” , to find the factorial.
STEP 2: Start by validating the input using the “If Else” Statement, if the input is less than ‘0’,
return an error message “Invalid Number”.
STEP 3: Check for the base case
. If the value of ‘n’ is ‘0’, return 1.
i. If the value of ‘n’ is 1, return ‘1’ (FACTORIAL OF “0 AND 1” IS 1)
STEP 4: Check for the Recursive case:
.Else recursively call the “factorial” function which evaluates as follows
1. Multiply the number n by the factorial value of ‘n-1’.
2. Repeat the recursive call till it reaches the base case(1).

1
STEP 5: Display the factorial of a given number as output.
CODE:

import java.util.*; public class


factorialRecursion{ public static void
main(String[] args){
System.out.println("PROGRAM TO FIND THE FACTORIAL OF A GIVEN NUMBER USING
RECURSION");
System.out.println("ENTER THE NUMBER TO FIND THE FACTORIAL OF A GIVEN
NUMBER USING RECURSION");
Scanner in = new Scanner(System.in);
int n= in.nextInt(); if(n<0)
{
System.out.println("Invalid Number");
}
else
System.out.println("FACTORIAL OF A GIVEN NUMBER IS: " +factorial(n));
}
static int factorial(int n)
{ //factorial program
if(n==0 || n==1) return
1;
else
return n*factorial(n-1);
}
}
OUTPUT:
EXECUTION 1

2
EXECUTION 2:

EXECUTION 3:

TIME COMPLEXITY
The Time Complexity for finding the factorial of a given number using recursion is O(N)

EXACT TIME COMPLEXITY


The Exact Time Complexity for finding the factorial of a given number using recursion is
O(5)

3
RESULT:
Thus, the program for finding the factorial using recursion has been executed and verified
successfully.

4
5
EX. NO: 2 REVERSING A STRING USING RECURSION DATE :

Aim:
To write a Java function to reverse a string using Recursion and specify its Time
Complexity.
TASK 1:Creating the Class“stringReverse”

● Import the util package


● Create a class named” stringReverse”.

TASK 2: Creating the Main Function

● Using the “scanner class” object “input”gets the input for reversing the String.
● Assign the input received from the input source to astring variable “str”.
● Print the Reversed String by passing the parameter str, empty string (“ ”) as
reversed, “0” as starting index, and “str.length()-1” as end index.

ALGORITHM:

Implement the reverseString Recursive Function.

STEP 1: Include the parameter “str”, “reversed”, “startIndex”, and ” endIndex” to reverse the
String.

STEP 2:Check Base Case: Use “If Statement” to Check whether the “startIndex” is greater
than the “endIndex”, terminate and return the empty string as output.

STEP 3:Check for Recursive Case: Recursively invoke reverseString function and append
the “endIndex” character with the“reversed”

STEP 4: Return the reverseString function by passing the parameter “str”, ”reversed”,”
startIndex”,” endIndex-1”

STEP 5: Display the reversed string as output


CODE:

1
import java.util.Scanner;

public class stringReverse

{ public static void main(String[]

args)

System.out.println("PROGRAM TO REVERSE A STRING USING RECURSION");

System.out.println("ENTER THE STRING TO BE REVERSED USING RECURSION");

Scanner input = new Scanner(System.in);

String str = input.nextLine();

String reversed="";

System.out.println("THE REVERSED STRING IS: " +reverseString(str,"",0,str.length()-1) );

public static String reverseString(String str, String reversed, int startIndex, int

endIndex) { // Base Case if (startIndex >endIndex) { return reversed;

// Recursive Step reversed += str.charAt(endIndex); return

reverseString(str, reversed, startIndex, endIndex - 1);}

}
OUTPUT:

EXECUTION 1

2
TIME COMPLEXITY
The Time Complexity to reverse a string using Recursion is O(N)

EXACT TIME COMPLEXITY


The Exact Time Complexity to reverse a string using Recursion is O(15)

3
RESULT:

Thus, the program for reversing a string has been executed and verified successfully

4
EX. NO:3 FIND THE SECOND-HIGHEST NUMBER IN AN ARRAY DATE :
Aim:
To write a Java function to find the second-highest number in an array and specify its Time
Complexity.

TASK 1: Creating the Class“secondLargest”

● Import the util package


● Create a class named” secondLargest”.
TASK 2: Creating the Main Function

● Using the “scanner class” object “sc”gets the input size for finding the second
highest number.
● Assign the input sizereceived from the input source to aninteger variable “n”.
● Do Inline Initialization for array variable “arr” of “n” Size.
● Use the “for loop” to get the n inputs from the user, limits to the size “n”.
● Within the “for loop” Use the “scanner class” object “sc.nextInt” to get the input
and assign it to variable “arr[i]”.
● Assign the findSecondLargest(arr) function to the integer
variable
“secondLargest:
● Print the Second Largest number by passing the array “arr” as the parameter.
ALGORITHM:

Implement the findSecondLargest Function.


STEP 1: Include the parameter array “arr”to find the Second-highest number in the array.
STEP 2: Do Inline Initialization: “Integer.MIN.VALUE” to the variables “max” and
“secondMax”
STEP 3: Traverse the array in a loop starting at index 0.
STEP 3.1: Compare each element of the array with the value stored in the variable “max”
STEP 3.1.1: If the value in the variable” max” is less than the array value.
a. assign the value of the variable” max” to “secondMax”
b. assign the value of the array variable arr[i] to variable “max”
STEP 3.1.2. Else If the value in the variable” secondMax” is less than the array value
a. assign the value of the array to variable “secondMax”
STEP 4: Return the “secondMax” .
STEP 5: Display the Second Highest number as output.
CODE:

import java.util.*; public


class secondLargest
{
public static void main(String args[])
{
System.out.println("PROGRAM FOR FINDING THE SECOND HIGHEST NUMBER IN
AN ARRAY");
System.out.println("\nENTER THE SIZE OF THE
ARRAY"); Scanner sc = new Scanner(System.in); int n =
sc.nextInt(); int[] arr = new int[n];
System.out.println("ENTER THE ELEMENTS OF THE ARRAY");
for (int i = 0; i< n; i++)
{
arr[i] = sc.nextInt();
}
int secondLargest = findSecondLargest(arr);
System.out.println("The Second Highest Number is "+ secondLargest);
}
static int findSecondLargest(int[] arr)
{ int max=Integer.MIN_VALUE; int
secondMax=Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++)
{ if(max<arr[i
])
{
secondMax=max;
max=arr[i];
}
else if(secondMax<arr[i])
{
secondMax=arr[i];
}
}
return(secondMax);
}
}
OUTPUT:
EXECUTION 1:

TIME COMPLEXITY:
The Time Complexity to find the second highest number in an array is O(N)

EXACT TIME COMPLEXITY:


The Exact Time Complexity to find the second highest number in an array is O(5)
RESULT:
Thus, the program for finding the second-highest number in an array has been executed and
verified successfully.

EX. NO: 4 ARRAY INSERTION AT GIVEN POSITION DATE :

Aim:
To write a Java function to perform array insertion at a given position and specify its
Time Complexity.
TASK 1: Creating the Class“Array_Insertion”
● Import the util package
● Create a class named” Array_Insertion”.
TASK 2: Creating the Main Function

● Declare the following integer variables o Variable” len” for storing the length of

the array o Variable “p” for getting position to insert the new element in the array.

o Variable “e” for getting the element to be inserted inthe given position.

● Using the “scanner class” object “sc” get the length of the array and elements of
the array.
● Increase the length of the array to add the new element by using “len+1” and assign
it to the integer array variable “ arr[]”.
● Use the “for loop” to get the elements of the array limiting to the length “len”.
● Within the “for loop” Use the “scanner class” object “sc.nextInt” to get the input
and assign it to variable “arr[i]”.
● Get the position of the element to be inserted in the array using the variable “p”.
● Get the element to be inserted in the array using the variable “e”.
● Call the arrayInsert() by passing the parameter “arr,p,e,len”.
ALGORITHM:

Implement the arrayInsert Function.


STEP 1: Include the parameters:”arr”,”p”,”e”,”len” to insert a new element in an array at a given
position.
STEP 2:Use the “for loop”that Starts with the last element of the array and iterates backward up
to the position p-1
STEP 2.1:Within “for Loop” Shift one position of each element to the right to make space for
the new element.
STEP 3:Assign the new element variable“e”to the position p-1.
STEP 4:Display the updated length of the array (increase by 1).
STEP 5: Display the elements of the modified array
CODE:

import java.util.Scanner;

public class Array_Insertion {

public static void main(String[] args)


{ int len,p,e;
System.out.println("ARRAY OPERATION");
Scanner sc=new Scanner(System.in);
System.out.println("Enter the length of the
Array"); len=sc.nextInt(); int arr[]=new int[len+1];
System.out.println("Enter "+len+" element(s) to insert");
for(int i=0;i<len;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Enter the position where you want to insert:");
p=sc.nextInt();
System.out.println("Enter the element to be
inserted"); e=sc.nextInt(); arrayInsert(arr,p,e,len);
}
static void arrayInsert(int[] arr,int p,int e,int len)
{
for(int i=len-1;i>=(p-1);i--)
{ arr[i+1]=arr[i];
} arr[p-
1]=e;
System.out.println("After Inserting");
System.out.println("Length of the array:"+(len+1));
for(int i=0;i<=len;i++)

{
System.out.println("arr["+i+"]="+arr[i]);
}
}
}
OUTPUT:
EXECUTION 1:

TIME COMPLEXITY:
The Time Complexity to find the second highest number in an array is O(N)

EXACT TIME COMPLEXITY:


The Exact Time Complexity to find the second highest number in an array is O(5)
RESULT:

Thus, the program for finding the second-highest number in an array has been executed and
verified successfully.
EX. NO: 5 LENGTH OF THE LINKEDLIST
DATE :
Aim:
To write a Java function to find the length of the singly linked list and specify its Time
Complexity.

TASK 1: Creating the Class “linkedList”


● Import the util package
● Create a class named” linkedList”.
TASK 2: Create a Node class:
● Define a class Node with integer data and a reference to the next node (next).
● Include a constructor to initialize the node with the given data.
TASK 3: Initialize head and tail in LinkedList class:
● In the LinkedList class, initialize both head and tail to null.
TASK 4: Creating addNode() Function
● Create a new node for the data.
● If the linked list is empty (head is null), set both head and tail to the new node.
● If the linked list is not empty, add the new node after the current tail and update the
tail to the new node.
TASK 5: Creating the Main Function
● Using the “scanner class” object “sc” get the elements of the LinkedList.
● Display a message prompting the user to enter integers to create nodes.
● Create a “While loop” that continues as long as the user inputs as integers
● Inside the loop o Read the next integer using the Scanner method.

o Invoke the addnode() to add a node in the Linked list.

● Display a message indicating that the linked list has been created.
o Print the contents of the linked list using a displayList method

(assuming it's defined in the LinkedList class).


o Calculate and print the length of the linked list using a length method.

TASK 6: Creating displayList() Function


● Initialize the “current” pointer to the head of the linked list.
● While current is not null:
o Print the data of the current node followed by an “arrow. “ o Move the

current pointer to the next node

● Print "null" to represent the end of the linked list.

ALGORITHM:
Implement the Length Function.
STEP 1: Initialize Variable “count to 0”and set“current” to the head of the linked list.
STEP 2: Traverse the Linked List Using a “while loop” to travel as long as the current is
not null.
● Inside the loop Increment count by 1.
● Move current to the next node in the linked list.
STEP 3: Return thefinal value of count as the length of the linked list.
CODE:
import java.util.Scanner;
public class LinkedList {
class Node
{ int data;
Node next; public
Node(int data)
{ this.data = data;
this.next = null;
}
}

Node head = null;


Node tail = null;

public void addNode(int data) {


Node newNode = new
Node(data); if (head == null) {
head = newNode; tail =
newNode;
} else {
tail.next = newNode;
tail = newNode;
}
} public static void main(String[]
args) {
LinkedList list = new LinkedList();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter integers to create nodes (enter a non-integer to exit):");
while (scanner.hasNextInt()) {
int data = scanner.nextInt();
list.addNode(data);
}
System.out.println("Linked List created");
System.out.println("Linked List");
list.displayList();
System.out.println("Length of the Linked List is:"+list.length());
scanner.close();
} int
length()
{ int count =0; Node
current =this.head;
while(current !=null)
{ count++; current
=current.next;
} return
count; }
public void displayList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
}
OUTPUT:
EXECUTION I
TIME COMPLEXITY:

The Time Complexity to find the length of the Linked List is O(N)

EXACT TIME COMPLEXITY:


The Exact Time Complexity to find the length of the Linked List is O(3)
RESULT:
Thus, the program for finding the length of the Linked List has been executed and verified
successfully.
EX. NO: 6 INSERTING ANODE AT THE MIDDLE OF THE LINKED LIST DATE :

Aim:
To write a Java function to perform the insert at middle operation in the singly linked list
and specify its Time Complexity.
.
TASK 1: Creating the Class “linkedList”
● Import the util package
● Create a class named” linkedList”.
TASK 2: Create a Node class:
● Define a class Node with integer data and a reference to the next node (next).
● Include a constructor to initialize the node with the given data.
TASK 3: Initialize head and tail in LinkedList class:
● In the LinkedList class, initialize both head and tail to null.
TASK 4: Creating addNode() Function
● Create a new node for the data.
● If the linked list is empty (head is null), set both head and tail to the new node.
● If the linked list is not empty, add the new node after the current tail and update the
tail to the new node.
TASK 5: Creating the Main Function
● Using the “scanner class” object “sc” get the elements of the LinkedList.
● Display a message prompting the user to enter integers to create nodes.
● Create a “While loop” that continues as long as the user inputs.
● Inside the loop o Read the next integer using the Scanner method.

o Invoke the addnode() to add a node in the Linked list.

● Display a message indicating that the linked list has been created.
o Print the contents of the linked list using a displayList method

(assuming it's defined in the LinkedList class).


o Read the integer value to find the position of the element to be inserted

using the variable “pos”(can use “If Statement”).


o Read the integer value to insert the data at the given position using the

variable “data”.

TASK 6: Creating displayList() Function


● Initialize the “current” pointer to the head of the linked list.
● While current is not null:
o Print the data of the current node followed by an “arrow. “ o Move the

current pointer to the next node

● Print "null" to represent the end of the linked list.

ALGORITHM:
Implement the Insert at middle Function.
STEP 1: Include the parameters “data” and “pos”with the Integer data type.

STEP 2: Create a new node with a variable “newNode” with the given data.

STEP 3: Initialize a temporary node with the variable “temp” pointing to the head of the
linked list.

STEP 4: Check whether the specified position “pos = 1” using “IF Statement”:

STEP 4.1: If true, set “newNode.next” to the current head, and update the head to the new
node.

STEP 4.2:If false, proceed to the next step.

STEP 5: If the position is not 1, iterate through the linked list until reaching the node just
before the desired position:

STEP 5.1:Use a “For loop” to traverse the list for "pos-1” times.

STEP 5.2:Update the variable “temp” node to point to the desired position.

STEP 6:Insert the new node “newNode” into the linked list:

STEP 6.1:Set variable “newNode.next” to the current node at the desired position.
STEP 6.2:Update the next reference of the “temp” node to point to the new node.
STEP 7:Display a message prompting the “Element Inserted” to indicate the successful
insertion.
CODE:
import java.util.Scanner;
public class LinkedList {
class Node
{ int data;
Node next;

public Node(int data)


{ this.data = data;
this.next = null;
}
}

Node head = null;


Node tail = null;

public void addNode(int data)


{ Node newNode = new
Node(data); if (head == null)
{ head = newNode; tail =
newNode;
} else
{ tail.next =
newNode; tail =
newNode;
}
}

public static void main(String[] args) {


LinkedList list = new LinkedList();
Scanner sc = new Scanner(System.in); int
pos=0; int data,data1;
System.out.println("ENTER INTEGERS TO CREATE NODES (ENTER A
NON-INTEGER TO EXIT):");
while (sc.hasNext())
{

if(sc.hasNextInt())
{
data = sc.nextInt();
list.addNode(data);
}
else
{
String temp=sc.next();
System.out.println("LINKED LIST CREATED");
System.out.println("LINKED LIST BEFORE INSERTING");
list.displayList();
System.out.println("ENTER THE POSITON WHERE YOU WANT TO INSERT");
if(sc.hasNextInt())
{
pos=sc.nextInt();
System.out.println("ENTER THE ELEMENT TO BE INSERTED:");
if(sc.hasNextInt())
{ data1=sc.nextInt();
list.insertMiddle(data1,pos)
;
System.out.println("LINKED LIST AFTER INSERTING");
list.displayList();
}
else
{
System.out.println("Enter integers only");
System.exit(0);
}
}
else
{
System.out.println("Enter integers only");
System.exit(0);
}
}
}
} public void insertMiddle(int data,int
pos)
{
//Create a new node
Node newNode = new Node(data);
//temporary node points to head node
Node temp=head;
if(pos==1)
{
newNode.next=temp;
head=newNode;
} else { for(int i=1;i<(pos-
1);i++ )
{
temp = temp.next;
} newNode.next=temp.next;
temp.next=newNode;
}
System.out.println("Element Inserted");

public void displayList() {


Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
}
EXECUTION I

TIME COMPLEXITY:
The Time Complexity to Insert a node in the middle of the Linked List is O(N)

EXACT TIME COMPLEXITY:


The Exact Time Complexity to Insert anode in the middle of the Linked List is O(2)
RESULT:
Thus, the program for inserting a node in the middle of the Linked List has been executed and
verified successfully.
EX. NO: 7 INSERTING A NODE AT THE END OF THE LINKED LIST DATE :

Aim:
To write a Java function to perform the insertion at the end operation in the singly linked
list and specify its Time Complexity.
TASK 1: Creating the Class “linkedList”
● Import the util package
● Create a class named” linkedList”.
TASK 2: Create a Node class:
● Define a class Node with integer data and a reference to the next node (next).
● Include a constructor to initialize the node with the given data.
TASK 3: Initialize head and tail in LinkedList class:
● In the LinkedList class, initialize both head and tail to null.
TASK 4: Creating addNode() Function
● Create a new node for the data.
● If the linked list is empty (head is null), set both head and tail to the new node.
● If the linked list is not empty, add the new node after the current tail and update the
tail to the new node.
TASK 5: Creating the Main Function
● Using the “scanner class” object “sc” get the elements of the LinkedList.
● Display a message prompting the user to enter integers to create nodes.
● Create a “While loop” that continues as long as the user inputs as integers
● Inside the loop o Read the next integer using the Scanner method.

o Invoke the addnode() to add a node in the Linked list.

● Display a message indicating that the linked list has been created.
o Print the contents of the linked list using a displayList method

(assuming it's defined in the LinkedList class).


TASK 6: Creating displayList() Function
● Initialize the “current” pointer to the head of the linked list.
● While current is not null:
o Print the data of the current node followed by an “arrow. “
o Move the current pointer to the next node

● Print "null" to represent the end of the linked list.

ALGORITHM:

Implementing the inserting a node at the end of the linked list

STEP 1:Include the parameter “data” of the integer data type

STEP 2: Create a new node variable “newNode” with the given data.

STEP 3: Check whether the linked list is empty (head is null) using “IF Statement”

STEP 3.1: If true, set both head and tail to the new node.

STEP 3.2: If false, proceed to the next step.

STEP 4: Initialize a temporary pointer “temp” to the head of the linked list.

STEP 5: Traverse the linked list using a while loop until “temp.next” is null.

STEP 5.1: Within the loop, move” temp” to the next node.

STEP 5.2: Set “temp.next” to the new node.

STEP 6: Display a message prompting the “Elements Inserted” to indicate the successful
insertion

CODE:

import java.util.Scanner;

public class LinkedList {


class Node
{ int data;
Node next;
public Node(int data)
{ this.data = data;
this.next = null;
}
}

Node head = null;


Node tail = null;

public void addNode(int data)


{ Node newNode = new
Node(data); if (head == null)
{ head = newNode; tail =
newNode;
} else { tail.next =
newNode; tail =
newNode;
}
}

public static void main(String[] args) {


LinkedList list = new LinkedList();
Scanner sc = new Scanner(System.in);

int pos=0;
int data,data1;
System.out.println("ENTER INTEGERS TO CREATE NODES (ENTER A NON-INTEGER
TO EXIT):");

while (sc.hasNext())
{
if(sc.hasNextInt())
{ data =
sc.nextInt();
list.addNode(data);
}
else
{
String temp=sc.next();
System.out.println("LINKED LIST CREATED");
System.out.println("LINKED LIST BEFORE INSERTING");
list.displayList();
System.out.println("ENTER THE ELEMENT TO BE INSERTED:");
if(sc.hasNextInt())
{
data1=sc.nextInt();
list.insertEnd(data1);
}
else{
System.out.println("Enter integers only");
System.exit(0);
}
System.out.println("LINKED LIST AFTER INSERTING");
list.displayList();
}
}
} public void insertEnd(int
data)
{
//Create a new node
Node newNode = new Node(data);
//Checks if the list is empty
if(head == null)
{
//If list is empty, both head and tail will point to new
node head = newNode; tail = newNode;
}
else
{
Node temp=head;
while( temp.next!=
null)
{
temp = temp.next;
}
temp.next=newNode;
System.out.println("Element Inserted");
}
}

public void displayList()


{ Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
}
OUTPUT:
EXECUTION I

TIME COMPLEXITY:
The Time Complexity to Insert a node at the end of the Linked List is O(N)

EXACT TIME COMPLEXITY:


The Exact Time Complexity to Insert a node at the end of the Linked List is O(4)

RESULT:
Thus, the program for inserting a node at the end of the Linked List has been executed and verified
successfully.

EX. NO: 8 DELETING A NODE AT THE END OF THE LINKED LIST DATE :

Aim:
To write a Java function to perform the deletion at tail operation in the singly linked list
and specify its Time Complexity.
TASK 1: Creating the Class “linkedList”
● Import the util package
● Create a class named” linkedList”.
TASK 2: Create a Node class:
● Define a class Node with integer data and a reference to the next node (next).
● Include a constructor to initialize the node with the given data.
TASK 3: Initialize head and tail in LinkedList class:
● In the LinkedList class, initialize both head and tail to null.
TASK 4: Creating addNode() Function
● Create a new node for the data.
● If the linked list is empty (head is null), set both head and tail to the new node.
● If the linked list is not empty, add the new node after the current tail and update the
tail to the new node.
TASK 5: Creating the Main Function
● Using the “scanner class” object “sc” get the elements of the LinkedList.
● Display a message prompting the user to enter integers to create nodes.
● Create a “While loop” that continues as long as the user inputs as integers
● Inside the loop o Read the next integer using the Scanner method.

o Invoke the addnode() to add a node in the Linked list.

● Display a message indicating that the linked list has been created.
o Print the contents of the linked list using a displayList method

(assuming it's defined in the LinkedList class).


TASK 6: Creating displayList() Function
● Initialize the “current” pointer to the head of the linked list.
● While current is not null:
o Print the data of the current node followed by an “arrow. “
o Move the current pointer to the next node

● Print "null" to represent the end of the linked list.

ALGORITHM:
STEP 1:Check whether the linked list is emptyusingthe “IF Statement”
STEP 1.1If true, display a message prompting the “List is Empty”.
STEP 1.2 If false, proceed to the next step.
STEP 2: Checkwhether there is only one node in the linked listusing “IF Statement”
STEP 2.1: If true, set head to null.
STEP 2.2: If false, proceed to the next step.
STEP 3: Initialize two pointers, “temp” and “prev`”, both pointing to the head of the linked
list.
STEP 4: Traverse the linked list using a while loop until “temp.next.next” is null.
STEP 4.1: Within the loop, update “prev”pointer to point to the next node and update
the“temp” to the “temp.next”
STEP 5: After the loop, move “temp” to the last node.
STEP 6: Set“prev.next” to null, effectively removing the last node from the linked list.
STEP 7: Print the data of the deleted element (last node).
CODE:
import java.util.Scanner;
public class LinkedList {
class Node
{ int data;
Node next;

public Node(int data) {


this.data = data;
this.next = null;
}
}

Node head = null;


Node tail = null;

public void addNode(int data) { Node


newNode = new Node(data); if
(head == null) { head = newNode;
tail = newNode;
} else { tail.next =
newNode; tail =
newNode;
}
}

public static void main(String[] args)


{ LinkedList list = new LinkedList();
Scanner sc = new Scanner(System.in);

System.out.println("Enter integers to create nodes (enter a non-integer to exit):");

while (sc.hasNextInt()) {
int data = sc.nextInt();
list.addNode(data);
}
System.out.println("Linked List created");

System.out.println("Linked List Before Deleting");


list.displayList();
System.out.println("Deletion at Tail");
list.deleteEnd();
System.out.println("Linked List After Deleting at tail");
list.displayList(); sc.close();
} public void
deleteEnd()
{ if(head==null)
System.out.println("List is
empty"); else if(head.next==null)
head=null;
else
{
Node temp=head; Node
prev=head;
while(temp.next.next!
=null)
{ prev=prev.next;
temp=temp.next
;
}
temp=temp.next;
prev.next=null;
System.out.println("Deleted Element is:"+temp.data);
}

}
public void displayList() { Node current =
head; while (current != null)
{ System.out.print(current.data + " ->
"); current = current.next;
}
System.out.println("null");
}
}
OUTPUT:

EXECUTION I

TIME COMPLEXITY:
The Time Complexity to Deletea node at the end of the Linked List is O(N)

EXACT TIME COMPLEXITY:


The Exact Time Complexity to Deletea node at the end of the Linked List is O(2)

RESULT:
Thus, the program fordeletinga node at the end of the Linked List has been executed and verified
successfully.
EX. NO: 9 STACK USING ARRAY
DATE :

Aim:
To develop a Java functionto perform push (), Pop(), isEmpty(), and IsFull()
operations in Stack using an array, to check for overflow and Underflow status, and Display
the Elements after each operation. Specify its Time Complexity.
TASK 1: Creating the Class “ArrayStack”
● Import the util package
● Create a class named”ArrayStack”.
TASK 2: Initializations:
● Declare “Capacity” with Integer Datatype.
● Declare “stack” with Integer Array,
● Do Inline Initialization for variable “top=-1” with Integer Type
TASK 3: Create a parameterized Constructor “cap” for “ArrayStack” for accessing Global
Variable “Capacity”
● Assign “Cap” to “Capacity”
TASK 4: Create a Function “Size”
● Return top+1
TASK 5: Creating the Display Function
● Check whether the Stack is Empty by calling “isEmpty()” using the “IF” Statement
and Display a message prompting “Stack is Underflow. No elements to display in
Empty Stack”
● Else Display a message prompting “Stack Elements: Top of the Stack Element is”
● Iterate backward to print the Stack Elements Starting with “top”
TASK 6: Creating the Main Function
● Create a new instance of “ArrayStack” with the Specified Capacity ● Using the
“scanner class” object “sc” to perform Stack Operations.
● Display a menu with the options: Push, Pop, Display, and Exit using Switch
Statement
● Take user input for the chosen option.
● Call the corresponding operation based on User’s Choice
● Repeat the menu until the user chooses to Exit.

ALGORITHM I:PUSH FUNCTION:


STEP 1: Include the parameter “data” with integer datatype
STEP 2: Checkwhether the stack is full using the isFull() method by the “If” Statement.
STEP 3 If the stack is full, display a message prompting “Stack is Overflow. Not Possible to
insert in Full Stack”
STEP 4: If the stack is not full, increment the top pointer by 1 and insert the data at the new
top position in the stack array
STEP 5: Display a message prompting “element is inserted”
ALGORITHM II:POP FUNCTION:
STEP 1:Initialize data to a default value (e.g., -1)
STEP 2:Check whether the stack is empty using the isEmpty() method by “If” Statement
STEP 3:If the stack is empty, display a message prompting “Stack is Underflow. No
elements to be popped in Empty Stack”
STEP 4:If the stack is not empty, retrieve the element at the top of the stack, decrement the
top pointer, and store the data
STEP 5:Return the data, which will either be the retrieved element or the default value if the
stack is empty

ALGORITHMIII:ISFULL() FUNCTION:
STEP 1:Invoke Size() method to get the current size of the stack(top+1)
STEP 2:Compare the current size of the stack with the capacity(Maximum size of the stack)
STEP 2.1:If the current size is equal to the capacity, the stack is considered full, and the
method returns true
STEP 2.2:otherwise, it returns false

ALGORITHMIV:ISEMPTY() FUNCTION:
STEP 1:Checkwhether the top pointer of the stack is less than 0 using “If” Statement
STEP 1.1:If it is true the stack is considered empty, and the function returns true.
STEP 1.2:Otherwise, it returns false, indicating that the stack is not empty.
CODE:
import java.util.*; public
class ArrayStack{ protected
int capacity; protected int[]
stack; protected int top = -1;
public ArrayStack(int cap)
{ capacity = cap; stack =
new int[capacity];
} public int
size()
{ return (top+1);
}
public void push(int data)
{
if (isFull())
System.out.println("Stack is Overflow. Not possible to insert in Full stack");
else
{
stack[++top] = data;
System.out.println("Element is inserted");
}
}

public int pop()


{ int data=-
1; if
(isEmpty())
{
System.out.println("Stack is Underflow. No elements to be popped in Empty Stack");
}
else
{ da
ta =
stac
k[to
p];
top-
-;

} return
data; }

public booleanisFull()
{ return
(size()==capacity);
}

public booleanisEmpty()
{ return (top<0);
}
public void display()
{ if(isEmpty())
System.out.println("Stack is Underflow. No elements to display in Empty Stack");
else
{
System.out.println("Stack Elements:Top of the Stack Element is");
for(int i=top;i>=0;i--)
System.out.println(stack[i]);
}
}
public static void main(String[] args)
{
ArrayStack s=new ArrayStack(5);
Scanner sc=new Scanner(System.in);
int data,ch; do

{
System.out.println("\n1.Push");
System.out.println("2.Pop");
System.out.println("3.Display Stack");
System.out.println("4.Exit\n");
System.out.println("Enter your choice:");
ch=sc.nextInt();
switch(ch)
{ case 1:
System.out.println("Enter the element to insert:");
data=sc.nextInt();
s.push(data);
break;
case 2:
data=s.pop();
if(data!=-1)
System.out.println("Popped Element:"+data);
break;
case 3:
s.display();
break;
} }while(ch<4);
}
}
OUTPUT:
EXECUTION
TIME COMPLEXITY:
The Time Complexity for Inserting an Element in a Stack Using an Array isO(1)
The Time Complexity for Deleting an Element in a Stack Using an Array isO(1)
The Time Complexity for Stack isFUll() Using an Array is O(1)
The Time Complexity for Stack is isEmpty() Using an Array is O(1)
The Time Complexity for Displaying N Elements is O(N)

EXACT TIME COMPLEXITY:


The Exact Time Complexity for Inserting an Element in a Stack Using an Array is O(1)
The Exact Time Complexity for Deleting an Element in a Stack Using an Array is O(1)
The Exact Time Complexity for Stack isFUll() Using an Array is O(1)
The Exact Time Complexity for Stack is isEmpty() Using an Array is O(1)
The Exact Time Complexity for Displaying N Elements is O(5)

RESULT:
Thus, the program for Stack operations using arrayhas been executed and verified successfully.

EX. NO: 10 STACK USING LINKED LIST


DATE :

Aim:

To develop a Java function to perform the push and pop operation in Stack using a linked
list and specify its Time Complexity.

TASK 1: Creating the Class “linkedStack”


● Import the util package
● Create a class named” linkedStack”.
TASK 2: Create a Node class
● Define a class Node with integer data and a reference to the next node (next).
● Include a constructor to initialize the node with the given data.
TASK 3: Creating a Constructor “linkedStack”
● Declare the “top” node as a class variable
● Initialize the stack as empty in the constructor.
TASK 4: Creating displayStack() Function:
● Traverse the stack from top.
● Print each node's data followed by an arrow (->).
● Print "null" at the end of the stack.
TASK 5: Creating the Main Function
● Using the “scanner class” object “sc” get the elements of the LinkedList.
● Display a message prompting the user to “enter integers to create nodes”.
● Create a “While loop” that continues as long as the user inputs as integers
● Inside the loop o If the current input is an integer:

▪ Read the integer using nextInt().

▪ Push the integer onto the stack using the push method.

o If the current input is not an integer:

▪ Read the non-integer input as a string (stored in a temporary

variable).
▪ Print a message indicating the creation of the stack using a

linked list.

▪ Print a label for the stack.

▪ Display the current state of the stack using the displayStack

method.
● Display a menu with the options: Push, Pop, Display, and Exit using Switch
Statement
● Take user input for the chosen option.
● Call the corresponding operation based on User’s Choice ● Repeat the menu until
the user chooses to Exit.
ALGORITHM I: Creating ISEMPTY() :
STEP 1: Check whether the top pointer of the stack is equal to Null using “If” Statement
STEP 1.1: If it is true the stack is considered empty, and the function returns true.
STEP 1.2: Otherwise, it returns false, indicating that the stack is not empty.

ALGORITHM II: Creating PUSH Function:


STEP 1: Create a new node with the given data.
STEP 2: Set the new node's next reference to the current top.
STEP 3: Update the top to the new node.
ALGORITHM III: Creating POP Function:
STEP 1: Check if the stack is empty. If yes, print "Stack Underflow."
STEP 2: If not empty, retrieve the data from the top node.
STEP 3: Update the top to the next node.
STEP 4: Return the retrieved data.
CODE:
import java.util.*; public
class linkedStack {
class Node
{ int data;
Node next; public
Node(int data)
{ this.data = data;
this.next = null;
}
}
Node top;
linkedStack()
{ this.top = null;

} public boolean isEmpty()


{
if(top==null) return true;
else return false; }
public void push(int
data)
{
Node newNode = new
Node(data); newNode.next = top;
top = newNode; } public int pop()
{ int
data=-1;
if (isEmpty()) {
System.out.print("\n STACK IS UNDERFLOW");
}
else
{ data=top.data;
top =
top.next;
} return
data;
} public static void main(String[] args)
{
LinkedStack stack = new LinkedStack();
Scanner scanner = new
Scanner(System.in); Scanner sc = new
Scanner(System.in); int ch,data, c;
System.out.println("ENTER INTEGERS TO CREATE NODES (ENTER A
NON-INTEGER TO EXIT):");
while (scanner.hasNext())
{ if(scanner.hasNextInt())
{ data =
scanner.nextInt();
stack.push(data);
}
else{
String temp=scanner.next();
System.out.println("STACK USING LINKED LIST HAS BEEN CREATED");
stack.displayStack();
do
{
System.out.println("1.PUSH");
System.out.println("2.POP");
System.out.println("3.EXIT");
System.out.println("ENTER YOUR
CHOICE:"); ch= scanner.nextInt(); switch(ch)

{ case 1:
System.out.println("ENTER THE ELEMENT TO PUSH INTO
STACK:"); data=scanner.nextInt(); stack.push(data);
System.out.println("STACK ELEMENTS AFTER PUSH OPERATION
ARE:"); stack.displayStack(); break;
case 2:
data=stack.pop(); if(data!=-
1)
{
System.out.println("POPPED ELEMENT IS:"+data);
System.out.println("STACK ELEMENTS AFTER POP");
stack.displayStack();
}
break;
case 3:
System.exit(0);
}}while(ch<3);
}
}
scanner.close();
}
public void displayStack()
{ Node current = top;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
}
OUTPUT
EXECUTION I

TIME COMPLEXITY:
The Time Complexity for Inserting an Element in a Stack Using a Linked List is O(1)
The Time Complexity for Deleting an Element in a Stack Using a Linked List is O(1)
The Time Complexity for Stack is isEmpty() Using a Linked List is O(1)
The Time Complexity for Displaying N Elements is O(N)

EXACT TIME COMPLEXITY:


The Exact Time Complexity for Inserting an Element in a Stack Using a Linked List is O(1)
The Exact Time Complexity for Deleting an Element in a Stack Using a Linked List is O(1)
The Exact Time Complexity for Stack is isEmpty() Using a Linked List is O(1)
The Exact Time Complexity for Displaying N Elements is O(5)

RESULT:
Thus, the program for Stack operations using Linked List has been executed and verified
successfully.

EX. NO: 11 REVERSE A STRING USING STACK


DATE :
Aim:
To implement a Java function to Reverse a String in a Stack using an array and
specify its Time Complexity
TASK 1: Creating the Class “ArrayStack”
● Import the util package
● Create a class named” Array Stack”.
TASK 2: Initializations:
● Declare “Capacity” with Integer Datatype.
● Declare “stack” with Character Array,
● Do Inline Initialization for variable “top=-1” with Integer Type
TASK 3: Create a parameterized Constructor “cap” for “ArrayStack” for accessing Global
Variable “Capacity”
● Assign “len” to “Capacity”
TASK 4: Create a Function “Size”
● Return top+1
TASK 5: Creating the Push Function
● Include the parameter “data” with integer datatype
● Check whether the stack is full using the isFull() method by the “If”
Statement.
● If the stack is full, display a message prompting “Stack is Overflow. Not
Possible to insert in Full Stack”
● If the stack is not full, increment the top pointer by 1 and insert the data at the
new top position in the stack array
● Display a message prompting “Element is inserted in the stack using Push”
TASK 5: Creating the Pop Function
● Initialize data of Character data type to a default value (e.g., 0)
● Check whether the stack is empty using the isEmpty() method by “If”
Statement
● If the stack is empty, display a message prompting “Stack is Underflow. No
elements to be popped in Empty Stack”
● If the stack is not empty, retrieve the element at the top of the stack, decrement
the top pointer, and store the data
● Return the data, which will either be the retrieved element or the default value
if the stack is empty
TASK 6: Creating the isFull Function
● Invoke Size() method to get the current size of the stack(top+1)
● Compare the current size of the stack with the capacity(Maximum size of the
stack) o If the current size is equal to the capacity, the stack is considered full,
and the method returns true

▪ otherwise, it returns false

TASK 7: Creating the isEmpty Function


● Check whether the top pointer of the stack is less than 0 using the “If”
Statement o If it is true the stack is considered empty, and the function
returns true.

o Otherwise, it returns false, indicating that the stack is not empty.

TASK 8: Creating the Display Function


● Check whether the Stack is Empty by calling “isEmpty()” using the “IF”
Statement andDisplaying a message prompting “Stack is Underflow. No
elements to display in Empty Stack”
● Else Display a message prompting “Stack Elements:”
● Iterate backward to print the Stack Elements Starting with “top”

TASK 9: Creating the Main Function


● Display a message prompting “Enter the string to reverse:”
● Use the Scanner object “sc” to get the input String to be reversed and store it to
the variable “str” of the String data type.
ALGORITHM:
STEP 1: Create an empty stack (here, ArrayStack) with a size equal to the length of the
input string.
STEP 2: Iterate through each character of the input string and push it onto the stack.
STEP 3: Display the elements currently in the stack.
STEP 4: Reverse the String:
STEP 4.1: Iterate through the input string in reverse order.
STEP 4.2: For each character, use the pop operation to retrieve and print or store the
reversed string.
CODE:
import java.util.*; public
class ArrayStack{ public
char[] stack; public int
capacity; protected int top
= -1; public ArrayStack(int
len) {
capacity=len;
stack = new char[len];
} public int
size()
{ return (top+1);
}
public void push(char data)
{
if (isFull())
System.out.println("Stack is Overflow. Not possible to insert in Full
stack"); else stack[++top] = data;
} public void
pop()
{ char
data='0'; if
(isEmpty())
{
System.out.println("Stack is Underflow. No elements to be popped in Empty Stack");

}
else { data =
stack[top]; top--;
}
System.out.print(data);
}
public boolean isFull()
{ return (size()==capacity);
}
public boolean isEmpty()
{ return (top<0);
}

public void display()


{ if(isEmpty())
System.out.println("Stack is Underflow. No elements to display in Empty Stack");
else
{
System.out.println("Stack Elements");
for(int i=top;i>=0;i--)
System.out.println(stack[i]);
}
}

public static void main(String[] args)


{

Scanner sc=new Scanner(System.in);


System.out.println("Enter the string to reverse:");
String str=sc.nextLine();
ArrayStack arrstack=new ArrayStack(str.length());
for(int i=0;i<str.length();i++)
{ arrstack.push(str.charAt(i));
}
System.out.println("Element is inserted in Stack using push.");
arrstack.display();
System.out.println("Reversed string using pop:");
for(int i=str.length()-1;i>=0;i--)
{ arrstack.pop();
}

}
}
OUTPUT:
EXECUTION I

TIME COMPLEXITY:
The Time Complexity for Inserting an Element in a Stack Using an Array is O(1)
The Time Complexity for Deleting an Element in a Stack Using an Array is O(1)
The Time Complexity for Stack isFUll() Using an Array is O(1)
The Time Complexity for Stack is isEmpty() Using an Array is O(1)
The Time Complexity for Reversing a String is O(N)

EXACT TIME COMPLEXITY:


The Exact Time Complexity for Inserting an Element in a Stack Using an Array is O(1)
The Exact Time Complexity for Deleting an Element in a Stack Using an Array is O(1)
The Exact Time Complexity for Stack isFUll() Using an Array is O(1)
The Exact Time Complexity for Stack is isEmpty() Using an Array is O(1)
The Exact Time Complexity for Reversing a String is O(15)

RESULT:
Thus, the program for String reverse using Stack has been executed and verified successfully.
EX. NO: 12 QUEUE USING ARRAY
DATE :
Aim:
To write a Java function to perform the enqueue and dequeue underflow and overflow
status in the Queue using an array and specify its Time Complexity.

TASK 1: Creating the Class “ArrayQueue”


● Import the util package
● Create a class named” ArrayQueue”.
TASK 2: Initializations:
● Declare “Capacity” with Integer Datatype.
● Declare “Queue” with Integer Array.
● Do Inline Initialization for variable “front” and “rear” to -1” with Integer Type
TASK 3: Create a parameterized Constructor “cap” for “ArrayQueue” for accessing Global
Variable “Capacity”
● Assign “cap” to “Capacity”
● Initialize an Integer array “queue” to “capacity”
TASK 4: Create a Function “Size”
● Return rear+1

TASK 5: Creating the Display Function


● Check whether the Queue is Empty by calling “isEmpty()” using the “IF”
Statement andDisplaying a message prompting “Queue is Underflow. No
elements to display in Empty Queue”
● Else Display a message prompting “Queue Elements:”
● Iterate to print the Queue Elements Starting with “front” and ending with”
rear”

TASK 6: Creating the Main Function


● Create a new instance of “ArrayQueue” with the specified Capacity
● Using the “scanner class” object “sc” to perform Queue Operations.
● Display a menu with the options: Enqueue, Dequeue, Display, and Exit using
Switch Statement
● Take user input for the chosen option.
● Call the corresponding operation based on User’s Choice ● Repeat the menu
until the user chooses to Exit.

ALGORITHM I: Creating the Enqueue Function


STEP 1: Include the parameter “data” with integer datatype
STEP2: Check whether the queue is full using the isFull() method by the “If”
Statement.
STEP3: If the stack is full, display a message prompting “Queue is Overflow. Not
Possible to insert in Full Queue”
STEP4: If the Queue is not full, increment the rear pointer by 1 and insert the
data at the new rear position in the Queue array
STEP5: Display a message prompting “Element is inserted”
ALGORITHM II: Creating the Dequeue Function
STEP 1:Initialize data of Integer data type to a default value (e.g., -1)
STEP 2:Check whether the Queue is empty using the isEmpty() method by “If”
Statement
STEP 3:If the stack is empty, display a message prompting “Queue is Underflow.
No elements to be deleted in Empty Queue”
STEP 4: If the Queue is not empty, retrieve the element at the front of the queue,
increment the front pointer, and store the data
STEP 4.1: Return the data, which will either be the retrieved element or the default
value if the Queue is empty

ALGORITHM III: Creating the isFull Function


STEP 1: Invoke the Size() method to get the current size of the queue.
STEP 2: Compare the current size of the queue with the capacity (Maximum size
of the queue)
STEP 2.1If the current size is equal to the capacity, the queue is considered full,
and the method returns true
STEP 2.2otherwise, it returns false
ALGORITHM IV: Creating the isEmpty Function
STEP 1: Check whether the front pointer and rear pointer of the queue are equal
using the “If” Statement
STEP 1.1: If it is true the queue is considered empty, and the function returns true.
STEP 1.2: Otherwise, it returns false, indicating that the queue is not empty.
CODE:

import java.util.*; public


class ArrayQueue{ protected
int capacity; protected int[]
queue; protected int front=-
1; protected int rear= -1;
public ArrayQueue(int cap)
{ capacity = cap; queue =
new int[capacity];
} public int
size()
{ return (rear+1);
}
public void enQueue(int data)
{
if (isFull())
System.out.println("Queue is Overflow. Not possible to insert in Full Queue");
else
{
queue[++rear] = data;
System.out.println("Element is inserted");
}
}
public int deQueue()
{ int data=-
1; if
(isEmpty())
{
System.out.println("Queue is Underflow. No elements to be deleted in Empty Queue");

}
else { front++; data
= queue[front];
} return
data; }
public boolean isFull()
{ return
(size()==capacity);
}
public boolean isEmpty()
{ return
(front==rear);
}
public void display()
{ if(isEmpty())
System.out.println("Queue is Underflow. No elements to display in Empty Queue");
else
{
System.out.println("Queue Elements");
for(int i=front+1;i<=rear;i++)
System.out.print(queue[i]+"\t");
}
}
public static void main(String[] args)
{
ArrayQueue q=new ArrayQueue(5);
Scanner sc=new Scanner(System.in);
int data,ch;
do
{
System.out.println("1.EnQueue");
System.out.println("2.DeQueue");
System.out.println("3.Display Queue");
System.out.println("4.Exit");
System.out.println("Enter your
choice:"); ch=sc.nextInt(); switch(ch)
{ case 1:
System.out.println("Enter the element to insert:");
data=sc.nextInt();
q.enQueue(data);
break;
case 2:
data=q.deQueue(); if(data!=-
1)
System.out.println("Deleted
Element:"+data); break; case 3:
q.display();
break;
} }while(ch<4);
}
}
OUTPUT:
EXECUTION I:

TIME COMPLEXITY:
The Time Complexity for Inserting an Element in a Queue Using an Array is O(1)
The Time Complexity for Deleting an Element in a Queue Using an Array is O(1)
The Time Complexity for Queue isFUll() Using an Array is O(1)
The Time Complexity for Queue is isEmpty() Using an Array is O(1)
The Time Complexity for Displaying N Elements is O(N)
EXACT TIME COMPLEXITY:
The Exact Time Complexity for Inserting an Element in a Queue Using an Array is O(1)
The Exact Time Complexity for Deleting an Element in a Queue Using an Array is O(1)
The Exact Time Complexity for Queue isFUll() Using an Array is O(1)
The Exact Time Complexity for Queue is isEmpty() Using an Array is O(1)
The Exact Time Complexity for Displaying N Elements is O(5)

RESULT:
Thus, the program for Queue Operations been executed and verified successfully.
EX. NO: 13 QUEUE USING LINKED LIST
DATE :
Aim:
To write a Java function to perform the enqueue operation and dequeue in the Queue
using a Linked List and specify its Time Complexity.

TASK 1: Creating the Class “linkedQueue”


● Import the util package
● Create a class named” linkedQueue”.
TASK 2: Create a Node class:
● Define a class Node with integer data and a reference to the next node (next).
● Include a constructor to initialize the node with the given data.
TASK 3: Creating a Constructor “linkedQueue”
● Declare the “front” and “rear” node as a class variable ● Initialize the queue as
empty in the constructor.
TASK 4: Creating displayQueue() Function:
● Traverse the queue from top to bottom.
● Print each node's data followed by an arrow (->).
● Print "null" at the end of the queue.
TASK 5: Creating the Main Function
● Using the “scanner class” object “sc” get the elements of the LinkedList.
● Display a message prompting the user to “enter integers to create nodes”.
● Create a “While loop” that continues as long as the user inputs as integers
● Inside the loop o If the current input is an integer:

▪ Read the integer using nextInt().

▪Push the integer onto the stack using the push method. o

If the current input is not an integer:

▪ Read the non-integer input as a string (stored in a temporary

variable).
▪ Print a message indicating the creation of the stack using a

linked list.

▪ Print a label for the stack.

▪ Display the current state of the Queue using the displayQueue

method.
● Display a menu with the options: Enqueue, Dequeue Display, and Exit using
Switch Statement
● Take user input for the chosen option.
● Call the corresponding operation based on User’s Choice ● Repeat the menu
until the user chooses to Exit.
ALGORITHM I: Creating the Enqueue Function
STEP 1: Include the parameter “data” with integer datatype
STEP2: Check whether the queue is full using the isFull() method by the “If”
Statement.
STEP3: If the queue is full, display a message prompting “Queue is Overflow.
Not Possible to insert in Full Queue”
STEP4: If the Queue is not full, increment the rear pointer by 1 and insert the
data at the new rear position in the Queue array
STEP5: Display a message prompting “Element is inserted”
ALGORITHM II: Creating the Dequeue Function
STEP 1: Initialize data of Integer data type to a default value (e.g., -1)
STEP 2: Check whether the Queue is empty using the isEmpty() method by “If”
Statement
STEP 3: If the queue is empty, display a message prompting “Queue is Underflow.
No elements to be deleted in Empty Queue”
STEP 4: If the Queue is not empty, retrieve the element at the front of the queue,
increment the front pointer, and store the data

STEP 4.1:Return the data, which will either be the retrieved element or the default
value if the Queue is empty

ALGORITHM III: Creating the isEmpty Function


STEP 1: Check whether the front pointer and rear pointer of the queue are equal
using the “If” Statement
STEP 1.1: If it is true the queue is considered empty, and the function returns true.
STEP 1.2: Otherwise, it returns false, indicating that the queue is not empty.
CODE:
import java.util.*; public
class LinkedQueue {
class Node
{ int data;
Node next; public
Node(int data)
{ this.data = data;
this.next = null;
}
}
Node front;
Node rear;
LinkedQueue()
{ this.front = null;
this.rear = null; } public
boolean isEmpty()
{
if(front==null) return
true; else return false; }
public void enQueue(int
data)
{
Node newNode = new Node(data);
if (rear == null) {
front = rear = newNode;
return
; } else
{ rear.ne
xt =
newNode
; rear =
newNode
;
}
}
public int deQueue()
{
int data=-1; if
(isEmpty()) {
System.out.print("\nQueue Underflow");
}
else
{
Node temp = front;
data=temp.data;
front = front.next;
} if (front == null)
rear = null;
return data;
}

public static void main(String[] args) {


LinkedQueue queue = new LinkedQueue();
Scanner scanner = new
Scanner(System.in); Scanner sc = new
Scanner(System.in); int ch,data, c;
System.out.println("Enter integers to create nodes (enter a non-integer to exit):");
while (scanner.hasNext()) {
if(scanner.hasNextInt())
{ data =
scanner.nextInt();
queue.enQueue(data);
}
else
{
String temp=scanner.next();
System.out.println("Queue using Linked List
created"); System.out.println("Queue");
queue.displayQueue(); do
{
System.out.println("1.EnQueue");
System.out.println("2.DeQueue");
System.out.println("3.Exit");
System.out.println("Enter your
choice:"); ch= scanner.nextInt();
switch(ch)
{ case 1:
System.out.println("Enter the element to insert:");
data=scanner.nextInt();
queue.enQueue(data);
System.out.println("After
EnQueue"); queue.displayQueue();
break;
case 2:
data=queue.deQueue(); if(data!=-
1)
{
System.out.println("Deleted Element:"+data);
System.out.println("After DeQueue");
queue.displayQueue();
}
break;
case 3:
System.exit(0);
}}while(ch<3);
}
}
scanner.close(); } public void
displayQueue() { Node current = front;
while (current != null)
{ System.out.print(current.data + " -> ");
current = current.next; }
System.out.println("null");
}
}
OUTPUT:
EXECUTION I:

TIME COMPLEXITY:
The Time Complexity for Inserting an Element in a Queue Using an LinkedList is O(1)
The Time Complexity for Deleting an Element in a Queue Using an LinkedList is O(1)
The Time Complexity for Queue isFUll() Using an LinkedList is O(1)
The Time Complexity for Queue is isEmpty() Using an LinkedList is O(1)
The Time Complexity for Displaying N Elements is O(N)

EXACT TIME COMPLEXITY:


The Exact Time Complexity for Inserting an Element in a Queue Using an LinkedList is
O(1)
The Exact Time Complexity for Deleting an Element in a Queue Using an LinkedList is
O(1)
The Exact Time Complexity for Queue isFUll() Using an LinkedList is O(1)
The Exact Time Complexity for Queue is isEmpty() Using an LinkedList is O(1)
The Exact Time Complexity for Displaying N Elements is O(5)

RESULT:
Thus, the program for Queue Operations been executed and verified successfully.
EX. NO: 14 BINARY SEARCH
DATE :
Aim:
To write a Java function to Search the number using the Binary Search Method and
specify its Time Complexity.
TASK 1: Creating the Class “BinarySearch”
● Import the util package
● Create a class named” BinarySearch”.
TASK 2: Creating the Main Function
● Display a message prompting the user to enter the Size of the elements for
Binary Search.
● Using the “scanner class” object “in” get the input size for Binary Search and
Assign the input received from the input source to an integer variable “n”.
● Create an Array number to store the integers
● Display a message prompting the user to enter the integer elements for Binary
Search.
● Iterate through user inputs Using “For Loop” o check whether each input is

an Integer Using “IF Statements”, If Not, display an error message “ENTER


ONLY INTEGER VALUES” and
Exit the program
● Display a message prompting the user to enter the KEY VALUE for Binary
Search.
● Using the “scanner class” object “in” get the Key Element for Binary Search
and Assign the input received from the input source to an integer variable
“Key”
● Call the BinarySearchIterative Function with the array numbers and the key
value.
● Display whether the key element is found in the array and its position if found,
or indicate that it is not found Using “If Statement”.

ALGORITHM:
Implement the BinarySearchIterative Function.
STEP 1:Include the parameter integer array “A” and “data” to perform the Search operation.
STEP 2:Initialize the variable“low” to “0” and the variable “high” to the length of the array
minus 1.
STEP 3: Check whether the “low”is less than or equal to “high” using “While” loop.
a. Midpint: Calculate the midpoint(mid) as (low + high) / 2.
b. Compare: If the value at the midpoint is equal to the target, return the mid
value as the position of the key element.
c. Adjust boundaries:
i. If the value is less than the target, set low to midpoint + 1.
ii. If greater, set high to midpoint - 1.
STEP 4: If the loop ends, the target is not in the array.
CODE:
import java.util.*; public class
BinarySearch { public static void
main(String[] args)
{
System.out.print("BINARY SEARCH\n");
Scanner in = new Scanner(System.in);
System.out.println("ENTER THE NUMBER OF
ELEMENTS:"); int n=in.nextInt(); int[] numbers=new int[n];
System.out.println("ENTER THE INTEGER VALUES:");
for(int i=0;i<n;i++)
{
if(in.hasNextInt())
numbers[i]=in.nextInt();
else
{
System.out.println("Enter integer numbers only");
System.exit(0);
}
}
System.out.println("ENTER THE KEY VALUE TO BE SEARCHED IN BINARY SEARCH
LIST"); int key =
in.nextInt();
int res=BinarySearchIterative(numbers,key); if(res==-
1)
System.out.println(key + " IS NOT FOUND");
else
System.out.println(key + " FOUND IN THE ARRAY AT POSITION "+(res+1));
in.close();
}
public static int BinarySearchIterative(int[] A, int data) {
int low = 0, high = A.length-1,mid;
while (low <= high) {

mid = low + (high-low)/2; //To avoid


overflow if(A[mid] == data) return mid; else
if(A[mid] < data)
low = mid + 1; else
high = mid - 1;
} return -
1; }
}
OUTPUT:
EXECUTION I

TIME COMPLEXITY:
The Time Complexity to find an Element in an Array using Binary Search is O(Log N)

EXACT TIME COMPLEXITY:


The Exact Time Complexity to find an Element in an Array using Binary Search is O(Log 4)

RESULT:
Thus, the program for finding an Element in an Array using Binary Search has been executed
and verified successfully.

EX. NO: 15 SELECTION SORT


DATE :
Aim:
To implement a Java function to perform the Selection sort in a sequential Sorting
Method and specify its Time Complexity.
TASK 1: Creating the Class “SelectionSort”
● Import the util package
● Create a class named” SelectionSort”.
TASK 2: Creating the Main Function
● Display a message prompting the user to enter the Number of the elements for
Selection Sort.
● Using the “scanner class” object “scanner” gets the input size for Selection
Sort and Assign the input received from the input source to an integer variable
“size”.
● Create an Array “array” to store the integers
● Display a message prompting the user to enter the integer elements for
Selection Sort
● Iterate to get the inputs from the user to sort it using “For Loop”
● Print the Before Sorted array elements using the “for” loop ● Call the
SelectionSortIterative Function.
● Print the After Sorted array elements using the “for” loop
ALGORITHM:
Implement the SelectionSortIterative Function.
STEP 1: Include the parameter integer array “arr” to perform the Selection Sort operation.
STEP 2: Get the Length of the Array and store it in the integer variable “n”.
STEP 3: Finding the Minimum Element Index:
STEP 3.1: Start the Outer loop starting from “o” to “n-1”.
STEP 3.2: Initialize minIndex with the current i.
STEP 3.3: Start the inner loop, j from i+1 to n , to find the index of the minimum element in
the unsorted portion.
STEP 3.4. Check whether the element at index j is less than the element at minIndex using
the “If” Statement
STEP 3.4.1: If True, update the minIndex with j.
STEP 3.5: Swap the element at minIndex with the element at the current i
STEP 4: Print the array after Sorting using the “For” Loop.
CODE:
import java.util.Scanner;

public class SelectionSort { public static void


selectionSortIterative(int[] arr) {
int n = arr.length;

for (int i = 0; i < n - 1; i++)


{ int minIndex = i;

for (int j = i + 1; j < n; j++) {


if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}

int temp = arr[minIndex];


arr[minIndex] = arr[i];
arr[i] = temp;

System.out.print("Array after iteration " + (i + 1) + ": ");


for (int k = 0; k < arr.length; k++) {
System.out.print(arr[k] + " ");
}
System.out.println();
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements:
"); int size = scanner.nextInt(); int[] array = new
int[size];
System.out.println("Enter the elements:");
for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}
System.out.print("Array before sorting: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
selectionSortIterative(array);
System.out.print("Array after sorting: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
OUTPUT:
EXECUTION I

TIME COMPLEXITY:
The Time Complexity to sort the Array using Selection Sort is O(N2)

EXACT TIME COMPLEXITY:


The Exact Time Complexity to sort the Array using Selection Sort is O(52 )

RESULT:
Thus, the program for sorting an element using Selection sort has been executed and verified
successfully.

You might also like