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

Data Structures Using Java Lab - SEZ31

The document discusses implementing a List ADT using linked lists in Java. It provides an algorithm to insert, delete and display elements in a linked list. It also includes the source code for a LinkedList class with methods to perform these operations and a MainList class with a menu driver to test the linked list implementation.

Uploaded by

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

Data Structures Using Java Lab - SEZ31

The document discusses implementing a List ADT using linked lists in Java. It provides an algorithm to insert, delete and display elements in a linked list. It also includes the source code for a LinkedList class with methods to perform these operations and a MainList class with a menu driver to test the linked list implementation.

Uploaded by

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

1.1.

LIST ADT USING ARRAYS

AIM:

To write a Java programs to implement the List ADT using arrays.

ALGORITHM:

Step 1: Start the program execution.


Step 2: Create a list with n number of elements.
Step 3: Insert() performs the inserting the element into the list.
Step 4: Delete() performs the deleting the element from the list.
Step 5: Insertfirst() used to insert the element in the first position of the list.
Step 6: Display the size of the array.
Step 7: Stop the program execution.

SOURCE CODE:

import java.util.Arrays;
import java.util.Scanner;

public class MyArrayList<T> {


private int size;
private int capacity;
private Object[] elements;

public MyArrayList() {
capacity = 10;
size = 0;
elements = new Object[capacity];
}

public void add(T element) {


if (size == capacity) {
expandCapacity();
}
elements[size++] = element;
}

public void add(int index, T element) {


if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("Index out of range!");
}

if (size == capacity) {
expandCapacity();
}

for (int i = size; i > index; i--) {


elements[i] = elements[i - 1];
}

elements[index] = element;
size++;
}

public void remove(int index) {


if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of range!");
}

for (int i = index; i < size - 1; i++) {


elements[i] = elements[i + 1];
}

size--;
}

public boolean remove(T element) {


int index = indexOf(element);
if (index != -1) {
remove(index);
return true;
}
return false;
}

public int indexOf(T element) {


for (int i = 0; i < size; i++) {
if (elements[i].equals(element)) {
return i;
}
}
return -1;
}

public boolean contains(T element) {


return indexOf(element) != -1;
}

public T get(int index) {


if (index >= 0 && index < size) {
return (T) elements[index];
}
throw new IndexOutOfBoundsException("Index out of range!");
}

public void set(int index, T element) {


if (index >= 0 && index < size) {
elements[index] = element;
} else {
throw new IndexOutOfBoundsException("Index out of range!");
}
}

public int size() {


return size;
}

private void expandCapacity() {


capacity *= 2;
elements = Arrays.copyOf(elements, capacity);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
MyArrayList<Integer> list = new MyArrayList<>();

int choice = -1;


do {
System.out.println("List Operations:");
System.out.println("1. Add element");
System.out.println("2. Add element at specific index");
System.out.println("3. Remove element at specific index");
System.out.println("4. Remove element");
System.out.println("5. Get element");
System.out.println("6. Set element");
System.out.println("7. Check if element exists");
System.out.println("8. Get size of list");
System.out.println("0. Exit");

System.out.print("Enter your choice: ");


choice = sc.nextInt();

switch (choice) {
case 1:
System.out.print("Enter the element to add: ");
int element1 = sc.nextInt();
list.add(element1);
break;
case 2:
System.out.print("Enter the index to add the element: ");
int index2 = sc.nextInt();
System.out.print("Enter the element to add: ");
int element2 = sc.nextInt();
list.add(index2, element2);
break;
case 3:
System.out.print("Enter the index to remove the element: ");
int index3 = sc.nextInt();
list.remove(index3);
break;
case 4:
System.out.print("Enter the element to remove: ");
int element4 = sc.nextInt();
list.remove(element4);
break;
case 5:
System.out.print("Enter the index to get the element: ");
int index5 = sc.nextInt();
Integer element5 = list.get(index5);
System.out.println("Element at index " + index5 + ": " + element5);
break;
case 6:
System.out.print("Enter the index to set the element: ");
int index6 = sc.nextInt();
System.out.print("Enter the new element: ");
int element6 = sc.nextInt();
list.set(index6, element6);
break;
case 7:
System.out.print("Enter the element to check if it exists: ");
int element7 = sc.nextInt();
boolean exists7 = list.contains(element7);
System.out.println("Element exists: " + exists7);
break;
case 8:
int size8 = list.size();
System.out.println("Size of list: " + size8);
break;
case 0:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice! Try again.");
break;
}

System.out.println();
} while (choice != 0);

sc.close();
}
}
OUTPUT

RESULT:

Thus, the above program has been executed successfully.


1.2.LIST ADT USING LINKED LIST

AIM:

To write a Java programs to implement the List ADT using linked list.

ALGORITHM:

Step 1: Start the program execution.


Step 2: Create a list with n number of elements.
Step 3: Insert() performs the inserting the element into the list.
Step 4: Delete() performs the deleting the element from the list.
Step 5: Insertfirst() used to insert the element in the first position of the list.
Step 6: Display the size of the linked list.
Step 7: Stop the program execution.

SOURCE CODE:

import java.util.Scanner;

class Node {
int data;
Node next;

public Node(int data) {


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

class LinkedList {
Node head;

public LinkedList() {
this.head = null;
}

public void insert(int data) {


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

public void insertAtFirst(int data) {


Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}

public void insertAtEnd(int data) {


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

public void insertAtLocation(int data, int location) {


if (location <= 0) {
System.out.println("Invalid location");
return;
}

Node newNode = new Node(data);


if (location == 1) {
newNode.next = head;
head = newNode;
} else {
Node currNode = head;
int count = 1;
while (currNode != null && count < location - 1) {
currNode = currNode.next;
count++;
}

if (currNode == null) {
System.out.println("Invalid location");
return;
}

newNode.next = currNode.next;
currNode.next = newNode;
}
}

public void deleteAtFirst() {


if (head == null) {
System.out.println("The list is empty");
return;
}

head = head.next;
}

public void deleteAtEnd() {


if (head == null) {
System.out.println("The list is empty");
return;
}

if (head.next == null) {
head = null;
return;
}

Node currNode = head;


while (currNode.next.next != null) {
currNode = currNode.next;
}
currNode.next = null;
}

public void deleteAtLocation(int location) {


if (location <= 0) {
System.out.println("Invalid location");
return;
}

if (location == 1) {
head = head.next;
return;
}

Node currNode = head;


int count = 1;
while (currNode != null && count < location - 1) {
currNode = currNode.next;
count++;
}

if (currNode == null || currNode.next == null) {


System.out.println("Invalid location");
return;
}

currNode.next = currNode.next.next;
}

public void display() {


if (head == null) {
System.out.println("The list is empty");
} else {
Node currNode = head;
System.out.print("List: ");
while (currNode != null) {
System.out.print(currNode.data + " ");
currNode = currNode.next;
}
System.out.println();
}
}
}

public class MainList {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
LinkedList list = new LinkedList();

while (true) {
System.out.println("\nMenu:");
System.out.println("1. Insert");
System.out.println("2. Insert at First");
System.out.println("3. Insert at End");
System.out.println("4. Insert at Specific Location");
System.out.println("5. Delete at First");
System.out.println("6. Delete at End");
System.out.println("7. Delete at Specific Location");
System.out.println("8. Display");
System.out.println("9. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter the element to be inserted: ");
int insertElement = scanner.nextInt();
list.insert(insertElement);
break;

case 2:
System.out.print("Enter the element to be inserted at first: ");
int insertElementAtFirst = scanner.nextInt();
list.insertAtFirst(insertElementAtFirst);
break;

case 3:
System.out.print("Enter the element to be inserted at end: ");
int insertElementAtEnd = scanner.nextInt();
list.insertAtEnd(insertElementAtEnd);
break;

case 4:
System.out.print("Enter the element to be inserted: ");
int insertElementAtLocation = scanner.nextInt();
System.out.print("Enter the location: ");
int location = scanner.nextInt();
list.insertAtLocation(insertElementAtLocation, location);
break;

case 5:
list.deleteAtFirst();
break;

case 6:
list.deleteAtEnd();
break;

case 7:
System.out.print("Enter the location: ");
int deleteLocation = scanner.nextInt();
list.deleteAtLocation(deleteLocation);
break;

case 8:
list.display();
break;

case 9:
scanner.close();
System.exit(0);

default:
System.out.println("Invalid choice");
break;
}
}
}
}

OUTPUT

RESULT:

Thus, the above program has been executed successfully.


2.1. IMPLEMENTATION OF STACK ADT USING SINGLY LINKED LIST

AIM:

To write a Java program to implement the Stack operations using Singly Linked Lists.

ALGORITHM:

Step 1: Start the execution.


Step 2: The push() method is used to insert an element on the top of the stack.
Step 3: The pop() method is used to remove the top most element from the stack.
Step 4: The display() method is used to display all the elements of the stack.
Step 5: Stop the execution.
SOURCE CODE:
import java.io.*;
import java.util.*;
class SNode
{
int data;
SNode next;
}
class Stack
{
Scanner s=new Scanner(System.in);
SNode top,temp;
Stack()
{
this.top = null;
}
void push()
{
temp = new SNode();
System.out.println("Enter Data :");
temp.data=s.nextInt();
temp.next = null;
if(top == null)
top = temp;
else
{
temp.next = top;
top = temp;
}
}
void pop()
{
if(top == null)
System.out.println("Stack is empty");
else
{
System.out.println("popped element = "+ top.data);
top = top.next;
}
}
void view()
{
if(top == null)
System.out.println("Stack is empty");
else
{
System.out.println("Elements of the stack are:");
for(temp = top; temp !=null; temp = temp.next)
System.out.println(temp.data);
}
}
void peek()
{
if(top ==null)
System.out.println("top of the stack="+top);
else
System.out.println("top of the stack="+top.data);
}
}
class StackDemo
{
public static void main(String[] args)
{
int ch;
Scanner s=new Scanner(System.in);
Stack ob = new Stack();
System.out.println("IMPLEMENTATION OF STACK USING LINKED LIST");
System.out.println();
System.out.println("1. Push 2. Pop 3. View 4. Peek 5.Exit");
do
{
System.out.println("enter your choice:");
ch = s.nextInt();
switch(ch)
{
case 1: ob.push();break;
case 2: ob.pop();break;
case 3: ob.view();break;
case 4: ob.peek();break;
case 5: System.exit(0);
}
}while(ch<=5);
}
}

OUTPUT:

E:\csjava2a>javac StackDemo.java
E:\csjava2a>java StackDemo
IMPLEMENTATION OF STACK USING LINKED LIST
1. Push 2. Pop 3. View 4. Peek 5.Exit
enter your choice:
1
Enter Data :
10
enter your choice:
1
Enter Data :
20
enter your choice:
1
Enter Data :
30
enter your choice:
3
Elements of the stack are:
30
20
10
enter your choice:
2
popped element = 30
enter your choice:
4
top of the stack=20

RESULT:

Thus, the Java program to implement the Stack operations using Singly Linked List has been
executed successfully.
2.2. IMPLEMENTATION OF QUEUE ADT USING SINGLY LINKED LIST

AIM:

To write a Java program to implement the Queue operations using Singly Linked Lists.

ALGORITHM:

Step 1: Start the execution.


Step 2: The insert() method is used to add the element at the rear of the queue.
Step 3: The delete() method is used to remove the element at the front of the queue.
Step 4: The peek() method is used to return the first element at the front of the queue.
Step 5: The display() method is used to display all the elements of the queue.
Step 6: Stop the execution.
SOURCE CODE:
import java.io.*;
import java.util.*;
class QNode
{
int data;
QNode next;
}
class Queue
{
Scanner s=new Scanner(System.in);
QNode temp,rear,front;
Queue()
{
this.rear = this.front=null;
}
void enqueue()
{
temp = new QNode();
System.out.println("Enter Data :");
temp.data=s.nextInt();
temp.next = null;
if(rear == null)
front = rear = temp;
else
{
rear.next = temp;
rear = temp;
}
}
void dequeue()
{
if(front == null)
{
System.out.println("Queue is empty");
}
System.out.println("popped element = "+ front.data);
front = front.next;
}
void view()
{
if(front == null)
System.out.println("Queue is empty");
else
{
System.out.println("Elements of the Queue are:");
for(temp = front; temp !=null; temp = temp.next)
System.out.println(temp.data);
}
}
void getFront()
{
if(front == null)
System.out.println("Queue is empty");
else
System.out.println("front ="+front.data);
}
void getRear()
{
if(front == null)
System.out.println("Queue is empty");
else
System.out.println("rear ="+rear.data);
}
}
class QueueDemo
{
public static void main(String[] args)
{
int ch;
Scanner s=new Scanner(System.in);
Queue ob = new Queue();
System.out.println("IMPLEMENTATION OF QUEUE USING LINKED LIST");
System.out.println();
System.out.println("1. enqueue 2. dequeue 3. view 4. Front 5. Rear 6. Exit");
do
{
System.out.println("enter your choice:");
ch = s.nextInt();
switch(ch)
{
case 1: ob.enqueue();break;
case 2: ob.dequeue();break;
case 3: ob.view();break;
case 4: ob.getFront();break;
case 5: ob.getRear();break;
case 6: System.exit(0);
}
}while(ch<=6);
}
}

OUTPUT:
E:\csjava2a>javac QueueDemo.java
E:\csjava2a>java QueueDemo
IMPLEMENTATION OF QUEUE USING LINKED LIST
1. enqueue 2. dequeue 3. view 4. Front 5. Rear 6. Exit
enter your choice:
1
Enter Data :
10
enter your choice:
1
Enter Data :
20
enter your choice:
1
Enter Data :
30
enter your choice:
3
Elements of the Queue are:
10
20
30
enter your choice:
4
front =10
enter your choice:
5
rear =30
enter your choice:
2
popped element = 10
enter your choice:
3
Elements of the Queue are:
20
30
RESULT:
Thus, the Java program to implement the Queue operations using Linked List has been
executed successfully.
3.1. CONVERSION OF INFIX EXPRESSION INTO POSTFIX EXPRESSION
AIM:

To write a Java program to convert the given Infix expression to Postfix form using Stack.

ALGORITHM:
Step 1 : Start the execution.
Step 2 : Scan the infix notation from left to right one character at a time.
Step 3 : If the next symbol scanned as an operand, append it to the postfix string.

Step 4 : If the next symbol scanned is an operator, then:


i. Pop and append to the postfix string every operator on the stack that:

a. Is above the most recently scanned left parenthesis, and


b. Has precedence higher than or is a right-associative operator of equal
precedence to that of the new operator symbol.

Push the new operator onto the stack


Step 5 : If a left parenthesis is scanned, push it into the stack.

Step 6 : If a right parenthesis is scanned, all operators down to the most recently
scanned left parenthesis must be popped and appended to the postfix string. Furthermore, the pair
of parentheses must be discarded.
Step 7 : When the infix string is fully scanned, the stack may still contain some operators.
All the remaining operators should be popped and appended to the postfix string.

Step 8 : Stop the execution.

SOURCE CODE:
import java.util.*;
import java.util.Stack;
class Expression
{
static int prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}
static String conversion(String exp)
{
String result = new String("");
Stack <Character> st = new Stack<>();
for (int i = 0; i<exp.length(); ++i)
{
char c = exp.charAt(i);
if (Character.isLetterOrDigit(c))
result += c;
else if (c == '(')
st.push(c);
else if (c == ')')
{
while (!st.isEmpty() &&
st.peek() != '(')
result += st.pop();
st.pop();
}
else
{
while (!st.isEmpty() && prec(c) <= prec(st.peek()))
{
result += st.pop();
}
st.push(c);
}
}
while (!st.isEmpty())
{
if(st.peek() == '(')
return "Invalid Expression";
result += st.pop();
}
return result;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Infix to Postfix Expression Conversion");
System.out.println("Enter a Expression:");
String exp = s.next();
System.out.println("Postfix Expression:"+conversion(exp));
}
}
OUTPUT:

E:\csjava2a>javac Expression.java
E:\csjava2a>java Expression
Infix to Postfix Expression Conversion
Enter a Expression:
a*(b+c)/d
Postfix Expression:abc+*d/
RESULT:
Thus, the Java program to convert the given Infix Expression to postfix form using Stack has been executed
successfully.
3.2. EVALUATION OF POSTFIX EXPRESSION USING STACK ADT

AIM:

To write a Java program to evaluate the given Postfix Expression using Stack.

ALGORITHM:

Step 1 : Start the execution


Step 2 : Create a stack to store operands (or values)
Step 3 : Scan the given expression and do following for every sca nned element.
a) If the element is a number, push it into the stack
. b) If the element is a operator, pop operands for the operator from stack.
Evaluate the operator and push the result back to the stack
Step 4 : When the expression is ended, the number in the stack is the final answer
Step 5 : Stop the execution.

SOURCE CODE
import java.util.*;
import java.util.Stack;
class Postfix
{
static int evaluatePostfix(String exp)
{
Stack<Integer> stack=new Stack<>();
for(int i=0;i<exp.length();i++)
{
char c=exp.charAt(i);
if(Character.isDigit(c))
stack.push(c - '0');
else
{
int val1 = stack.pop();
int val2 = stack.pop();
switch(c)
{
case '+':
stack.push(val2+val1);
break;
case '-':
stack.push(val2- val1);
break;
case '/':
stack.push(val2/val1);
break;
case '*':
stack.push(val2*val1);
break;
}
}
}
return stack.pop();
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Expression Evaluation");
System.out.println("Enter a Expression:");
String exp = s.next();
System.out.println("postfix evaluation: "+evaluatePostfix(exp));
}}
OUTPUT:
E:\csjava2a>javac Postfix.java
E:\csjava2a>java Postfix
Expression Evaluation
Enter a Expression:
431*+5-
postfix evaluation: 2
RESULT:
Thus, the Java program to evaluate the Postfix expression using stack has been executed
successfully.
4. IMPLEMENTAION OF PRIORITY QUEUE ADT

AIM:
To write a java program to implement priority queue ADT.
ALGORITHM:
Step 1: Start the execution.
Step 2: The insert() method is used to add the element at the rear of the queue.
Step 3: The delete() method is used to remove the element at the front of the queue.
Step 4: The peek() method is used to return the first element at the front of the queue.
Step 5: The display() method is used to display all the elements of the queue.
Step 6: Stop the execution.
SOURCE CODE:
class Node
{
String data;
int prn;
Node next;
Node( String str, int p )
{
data = str; prn = p;
}
}
class LinkedPriorityQueue
{
Node head;
public void insert(String item, int pkey)
{
Node newNode = new Node(item, pkey);
int k;
if( head == null ) k =1;
else if( newNode.prn<head.prn) k =2;
else
k = 3;
switch( k )
{
case 1: head = newNode;
head.next = null; break;
case 2: Node oldHead = head;
head = newNode; newNode.next = oldHead; break;
case 3: Node p = head;
Node prev = p;
Node nodeBefore = null;
while( p != null )
{
if( newNode.prn<p.prn )
{
nodeBefore = p; break;
}
else
{
prev = p; p = p.next;
}
}
newNode.next = nodeBefore; prev.next = newNode;
}
}
public Node delete()
{
if( isEmpty() )
{
System.out.println("Queue is empty"); return null;
}
else
{
Node tmp = head; head = head.next; return tmp;
}
}
public void displayList()
{
Node p = head;
System.out.print("\nQueue: ");
while( p != null )
{
System.out.print(p.data+"(" +p.prn+ ")" + " ");
p = p.next;
}
System.out.println();
}
public boolean isEmpty()
{
return (head == null);
}
public Node peek()
{
return head;
}
}
class LinkedPriorityQueueDemo
{
public static void main(String[] args)
{
LinkedPriorityQueue pq = new LinkedPriorityQueue();
Node item;
pq.insert("Balu", 3);pq.insert("Vino",2);pq.insert("Ram",2);pq.insert("Sree", 1);
pq.insert("Suresh", 3); pq.displayList();item = pq.delete();
if( item != null )
System.out.println("delete():" + item.data + "(" +item.prn+")");pq.displayList();
pq.insert("Tino", 2);pq.insert("Lucky", 1); pq.insert("Mickey", 4); pq.displayList();
}
}

OUTPUT
RESULT:
Thus, the Java program to implement priority queue has been executed successfully.
5. (a) INSERTING AN ELEMENT INTO A BINARY SEARCH TREE

Aim:
To write a Java Program to insert an element into the Binary Search Tree.
Algorithm:
Step 1 : Start the execution
Step 2 : Read the value of n.
Step 3 : Using for loop, read the node elements one by one.
Step 4 : Start from the root.
Step 3 : Compare the element to be inserted with the root node.
Step 4 : If the value of the new node is less than the root node then, it will be inserted to the
left subtree.
Step 5 : If the value of the new node is greater than root node then, it will be inserted to the
right subtree.
Step 6 : On reaching the end node, insert the value left (if the value is smaller than current node
value), else right.
Step 7 : Stop the execution.

SOURCE CODE

class InsertBST {
// Class containing left and right child of current node and key value
class Node
{
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
// Root of BST
Node root;
// Constructor
InsertBST()
{
root = null;
}
// This method mainly calls insertRec()
void insert(int key)
{
root = insertRec(root, key);
}
/* A recursive function to
insert a new key in BST */
Node insertRec(Node root, int key)
{
/* If the tree is empty,
return a new node */
if (root == null)
{
root = new Node(key);
return root;
}
/* Otherwise, recur down the tree */
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
/* return the (unchanged) node pointer */
return root;
}
// This method mainly calls InorderRec()
void inorder()
{
inorderRec(root);
}
// A utility function to
// do inorder traversal of BST
void inorderRec(Node root)
{
if (root != null) {
inorderRec(root.left);
System.out.println(root.key);
inorderRec(root.right);
}
}
public static void main(String[] args)
{
InsertBST tree = new InsertBST();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
// print inorder traversal of the BST
tree.inorder();
}
}

OUTPUT:

E:\csjava2a>javac InsertBST.java
E:\csjava2a>java InsertBST
20
30
40
50
60
70
80
5. (b) DELETING AN ELEMENT INTO A BINARY SEARCH TREE

Aim:
To write a Java program to delete an element from a Binary Search Tree.

Algorithm:
Step 1 : Start the execution
Step 2 : Read the value of n.
Step 3 : Using for loop, read the node elements one by one.
Step 2 : Start from the root.
Step 3 : Compare the element to be inserted with the root node.
Step 4 : If the value of the new node is less than the root node then, it will be inserted to the left
subtree.
Step 5 : If the value of the new node is greater than root node then, it will be inserted to the
right subtree.
Step 6 : On reaching the end node, insert the value left (if the value is smaller than current
node value), else right.
Step 7 : Read the value of the node to be deleted.
Step 8 : When we delete a node, three possibilities arise.
i) Node to be deleted is the leaf: Simply remove from the tree.
ii) Node to be deleted has only one child: Copy the child to the node
and delete the child
iii) Node to be deleted has two children: Find inorder successor of the
node. Copy contents of the inorder successor to the node and delete the inorder successor.
Note that inorder predecessor can also be used.
Step 9 : Stop the execution.

SOURCE CODE

class DelBST
{
// A binary tree node
static class Node
{
int data;
Node left, right;
}
// A utility function to allocate a new node
static Node newNode(int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left = null;
newNode.right = null;
return (newNode);
}
static Node deleteLeaves(Node root, int x)
{
if (root == null)
{
return null;
}
root.left = deleteLeaves(root.left, x);
root.right = deleteLeaves(root.right, x);
if (root.data == x && root.left == null && root.right == null)
{
return null;
}
return root;
}
static void inorder(Node root)
{
if (root == null)
{
return;
}
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
public static void main(String[] args)
{
Node root = newNode(6);
root.left = newNode(5);
root.right = newNode(4);
root.left.left = newNode(1);
root.left.right = newNode(2);
root.right.right = newNode(5);
deleteLeaves(root, 5);
System.out.print("Inorder traversal after deletion : ");
inorder(root);
}
}

OUTPUT:

E:\csjava2a>javac DelBST.java
E:\csjava2a>java DelBST
Inorder traversal after deletion : 1 5 2 6 4
E:\csjava2a>
5.(c) SEARCHING FOR A KEY ELEMENT IN A BINARY SEARCH TREE

Aim:

To write a Java program to search an element in a Binary Search Tree.

Algorithm:

Step 1 : Start the execution.


Step 2 : Read the value of n.
Step 3 : Using for loop, read the node elements one by one.
Step 2 : Start from the root.
Step 3 : Compare the element to be inserted with the root node.
Step 4 : If the value of the new node is less than the root node then, it will be inserted to the left subtree.
Step 5 : If the value of the new node is greater than root node then, it will be inserted
to the right subtree.
Step 6 : On reaching the end node, insert the value left (if the value is smaller than current node value),
else right.
Step 7 : Read the value of the node to be searched.
Step 8 : Compare the element to be searched with the root node.
Step 9 : If the key (element to be searched) = root, return root node.
Step 10 : Else if key < root, traverse the left subtree.
Step 11 : Else traverse right subtree.
Step 12 : Repetitively compare subtree elements until the key is found or the end of the tree is reached.
Step 13 : If the element to search is found anywhere, return true, else return false.
Step 14 : Stop the execution.

SOURCE CODE

class SearchBST
{
static class Node
{
int data;
Node left, right;
Node(int data)
{
this.data = data;
left = right = null;
}
}
// Function to traverse the tree in preorder
// and check if the given node exists in it
static boolean ifNodeExists( Node node, int key)
{
if (node == null)
return false;
if (node.data == key)
return true;
// then recur on left subtree /
boolean res1 = ifNodeExists(node.left, key);
// node found, no need to look further
if(res1) return true;
// node is not found in left,
// so recur on right subtree /
boolean res2 = ifNodeExists(node.right, key);
return res2;
}
public static void main(String args[])
{
Node root = new Node(0);
root.left = new Node(1);
root.left.left = new Node(3);
root.left.left.left = new Node(7);
root.left.right = new Node(4);
root.left.right.left = new Node(8);
root.left.right.right = new Node(9);
root.right = new Node(2);
root.right.left = new Node(5);
root.right.right = new Node(6);
int key = 4;
if (ifNodeExists(root, key))
System.out.println("key is found");
else
System.out.println(key +"key is not found");
}
}

OUTPUT:

E:\csjava2a>javac SearchBST.java
E:\csjava2a>java SearchBST
key is found
6.(a) INSERTION INTO AN AVL TREE

AIM:

ALGORITHM:

SOURCE CODE:

class Node {
int data, height;
Node left, right;
Node(int item) {
data = item;
height = 1;
left = right = null;
}
}
// Class representing the AVL tree
class AVLTree {
Node root;
int height(Node node) {
if (node == null)
return 0;
return node.height;
}
int getBalance(Node node) {
if (node == null)
return 0;
return height(node.left) - height(node.right);
}
Node rotateRight(Node y) {
Node x = y.left;
Node T2 = x.right;
x.right = y;
y.left = T2;
y.height = Math.max(height(y.left), height(y.right)) + 1;
x.height = Math.max(height(x.left), height(x.right)) + 1;
return x;
}
Node rotateLeft(Node x) {
Node y = x.right;
Node T2 = y.left;
y.left = x;
x.right = T2;
x.height = Math.max(height(x.left), height(x.right)) + 1;
y.height = Math.max(height(y.left), height(y.right)) + 1;
return y;
}
Node insertNode(Node node, int data) {
if (node == null)
return new Node(data);
if (data < node.data)
node.left = insertNode(node.left, data);
else if (data > node.data)
node.right = insertNode(node.right, data);
else
return node;
node.height = 1 + Math.max(height(node.left), height(node.right));

int balance = getBalance(node);


if (balance > 1 && data < node.left.data)
return rotateRight(node);
if (balance < -1 && data > node.right.data)
return rotateLeft(node);
if (balance > 1 && data > node.left.data) {
node.left = rotateLeft(node.left);
return rotateRight(node);
}
if (balance < -1 && data < node.right.data) {
node.right = rotateRight(node.right);
return rotateLeft(node);
}
return node;
}
void preOrder(Node node) {
if (node != null) {
System.out.print(node.data + " ");
preOrder(node.left);
preOrder(node.right);
}
}
}
// Main class
public class MainAVL {
public static void main(String[] args) {
AVLTree tree = new AVLTree();
// Insert nodes into the AVL tree
tree.root = tree.insertNode(tree.root, 10);
tree.root = tree.insertNode(tree.root, 20);
tree.root = tree.insertNode(tree.root, 30);
tree.root = tree.insertNode(tree.root, 40);
tree.root = tree.insertNode(tree.root, 50);
tree.root = tree.insertNode(tree.root, 25);
// Print the AVL tree in pre-order traversal
System.out.println("Pre-order traversal of the constructed AVL tree:");
tree.preOrder(tree.root);
}
}
6.(b) DELETION TION INTO AN AVL TREE

AIM:

ALGORITHM:

SOURCE CODE:

class Node {
int key, height;
Node leftChild, rightChild;

Node(int value) {
key = value;
height = 1;
}
}

class AVLTree {
Node root;

int height(Node node) {


if (node == null)
return 0;
return node.height;
}

int getBalanceFactor(Node node) {


if (node == null)
return 0;
return height(node.leftChild) - height(node.rightChild);
}

Node minValueNode(Node node) {


Node current = node;
while (current.leftChild != null) {
current = current.leftChild;
}
return current;
}

Node rightRotate(Node y) {
Node x = y.leftChild;
Node T2 = x.rightChild;

x.rightChild = y;
y.leftChild = T2;

y.height = Math.max(height(y.leftChild), height(y.rightChild)) + 1;


x.height = Math.max(height(x.leftChild), height(x.rightChild)) + 1;
return x;
}

Node leftRotate(Node x) {
Node y = x.rightChild;
Node T2 = y.leftChild;

y.leftChild = x;
x.rightChild = T2;

x.height = Math.max(height(x.leftChild), height(x.rightChild)) + 1;


y.height = Math.max(height(y.leftChild), height(y.rightChild)) + 1;

return y;
}

Node deleteNode(Node root, int key) {


if (root == null)
return root;

if (key < root.key)


root.leftChild = deleteNode(root.leftChild, key);
else if (key > root.key)
root.rightChild = deleteNode(root.rightChild, key);
else {
if ((root.leftChild == null) || (root.rightChild == null)) {
Node temp;
if (root.leftChild != null)
temp = root.leftChild;
else
temp = root.rightChild;

if (temp == null) {
temp = root;
root = null;
} else
root = temp;
} else {
Node temp = minValueNode(root.rightChild);
root.key = temp.key;
root.rightChild = deleteNode(root.rightChild, temp.key);
}
}

if (root == null)
return root;

root.height = Math.max(height(root.leftChild), height(root.rightChild)) + 1;

int balanceFactor = getBalanceFactor(root);

if (balanceFactor > 1) {
if (getBalanceFactor(root.leftChild) >= 0)
return rightRotate(root);
else {
root.leftChild = leftRotate(root.leftChild);
return rightRotate(root);
}
}

if (balanceFactor < -1) {


if (getBalanceFactor(root.rightChild) <= 0)
return leftRotate(root);
else {
root.rightChild = rightRotate(root.rightChild);
return leftRotate(root);
}
}

return root;
}

void preOrder(Node node) {


if (node != null) {
System.out.print(node.key + " ");
preOrder(node.leftChild);
preOrder(node.rightChild);
}
}

public static void main(String[] args) {


AVLTree tree = new AVLTree();

/* Constructing tree given in the above figure */


tree.root = tree.insert(tree.root, 9);
tree.root = tree.insert(tree.root, 5);
tree.root = tree.insert(tree.root, 10);
tree.root = tree.insert(tree.root, 0);
tree.root = tree.insert(tree.root, 6);
tree.root = tree.insert(tree.root, 11);
tree.root = tree.insert(tree.root, -1);
tree.root = tree.insert(tree.root, 1);
tree.root = tree.insert(tree.root, 2);

System.out.println("Preorder traversal of constructed tree is : ");


tree.preOrder(tree.root);

tree.root = tree.deleteNode(tree.root, 10);

System.out.println("\nPreorder traversal after deletion of 10 :");


tree.preOrder(tree.root);
}
}
7.IMPLEMENTATION OF BFS FOR A GIVEN GRAPH

Aim:
To write a Java program to implement the BFS for a given graph.

Algorithm:
Step 1 : Start the execution.
Step 2 : Create an empty queue and push root node to it.
Step 3 : Do the following when the queue is not empty.
Step 4 : Pop a node from queue and print it.
Step 5 : Find neighbors of node with the help of adjacency matrix and check if node is
already visited or not.
Step 6 : Push neighbors of node into queue if not null
Step 7 : Stop the execution.
Program:
//Java Program to implement Breadth First Search on a graph non-recursively
//BreadthFirstSearch.java
import java.io.*;
import java.util.*;
public class BreadthFirstSearch
{
// Function to perform breadth first search
static void breadthFirstSearch(int[][] matrix, int source)
{
boolean[] visited = new boolean[matrix.length];
visited[source-1] = true;
Queue<Integer> queue = new LinkedList<>();
queue.add(source);
System.out.println("The breadth first order is");
while(!queue.isEmpty())
{
System.out.println(queue.peek());
int x = queue.poll();
int i;
for(i=0; i<matrix.length;i++)
{
if(matrix[x-1][i] == 1 && visited[i] == false)
{
queue.add(i+1);
visited[i] = true;
}
}
}
}
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int vertices;
System.out.println("Enter the number of vertices in the graph");
vertices = Integer.parseInt(br.readLine());
int[][] matrix = new int[vertices][vertices];
System.out.println("Enter the adjacency matrix");
for(int i=0; i<vertices; i++)
{
for(int j=0; j<vertices; j++)
{
matrix[i][j] = Integer.parseInt(br.readLine());
}
}
int source;
System.out.println("Enter the source vertex");
source = Integer.parseInt(br.readLine());
breadthFirstSearch(matrix,source);
}
}
Output:
Enter the number of vertices in the graph
3
Enter the adjacency matrix
0
0
0
1
0
1
1
1
1
Enter the source vertex
2
The breadth first order is
2
1
3
Result:
Thus, the Java program to implement the Breadth First Search for a graph has been executed
successfully.
8. IMPLEMENTATION OF DFS FOR A GIVEN GRAPH

Aim:
To write a Java program to implement the DFS for a given graph.

Algorithm:
Step 1: Start the execution.
Step 2: Create a stack of nodes and visited array.
Step 3: Insert the root in the stack.
Step 4: Run a loop till the stack is not empty.
Step 5: Pop the element from the stack and print the element.
Step 6: For every adjacent and unvisited node of current node, mark the node and insert it
in the stack.
Step 7: Stop the execution.
Program:
//Java Program to implement the Depth First Search for a Graph
//DepthFirstSearch.java
import java.io.*;
import java.util.*;
public class DepthFirstSearch
{
static void depthFirstSearch(int[][] matrix, int source)
{
boolean[] visited = new boolean[matrix.length];
visited[source-1] = true;
Stack<Integer> stack = new Stack<>();
stack.push(source);
int i,x;
System.out.println("The depth first order is");
System.out.println(source);
while(!stack.isEmpty())
{
x = stack.pop();
for(i=0; i<matrix.length; i++)
{
if(matrix[x-1][i] == 1 && visited[i] == false)
{
stack.push(x);
visited[i] = true;
System.out.println(i+1);
x = i+1;
i = -1;
}
}
}
}
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int vertices;
System.out.println("Enter the number of vertices in the graph");
vertices = Integer.parseInt(br.readLine());
int[][] matrix = new int[vertices][vertices];
System.out.println("Enter the adjacency matrix");
for(int i=0; i<vertices; i++)
{
for(int j=0; j<vertices; j++)
{
matrix[i][j] = Integer.parseInt(br.readLine());
}
}
int source;
System.out.println("Enter the source vertex");
source = Integer.parseInt(br.readLine());
depthFirstSearch(matrix,source);
}
}
Output:
Enter the number of vertices in the graph
3
Enter the adjacency matrix
0
0
0
1
0
1
1
1
1
Enter the source vertex
3
The depth first order is
3
1
2
Result:
Thus, the Java program to implement the Depth First Search for a graph has been executed
successfully.
9. (a) LINEAR SEARCH

AIM:

ALGORITHM:

SOURCE CODE:

import java.util.Scanner;
class LinearSearchExample
{
public static void main(String args[])
{
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter those " + n + " elements");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Element to search isn't present */
System.out.println(search + " isn't present in array.");
}
}

OUTPUT
9. (b) BINARY SEARCH
AIM:

ALGORITHM:

SOURCE CODE:

class BinarySearchExample
{
public static void binarySearch(int arr[], int first, int last, int key)
{
int mid = (first + last)/2;
while( first <= last )
{
if ( arr[mid] < key )
{
first = mid + 1;
}
else if ( arr[mid] == key )
{
System.out.println("Element is found at index: " + mid);
break; }
else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
public static void main(String args[])
{
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}

OUTPUT:
10. (a) BUBBLE SORT

AIM:

ALGORITHM:

SOURCE CODE:

public class BubbleSortExample


{
static void bubbleSort(int[] arr)
{
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
If(arr[j-1] > arr[j])
{
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args)
{
int arr[] ={3,60,35,2,45,320,5};
System.out.println("Array Before Bubble Sort");
for(int i=0; i < arr.length; i++){

System.out.print(arr[i] + " ");


}
System.out.println();
bubbleSort(arr);//sorting array elements using bubble sort
System.out.println("Array After Bubble Sort");
for(int i=0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}
OUTPUT
10. (b) SELECTION SORT

AIM:

ALGORITHM:

SOURCE CODE:

public class SelectionSortExample


{
public static void selectionSort(int[] arr)
{
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[index])
{
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String a[])
{
int[] arr1 = {9,14,3,2,43,11,58,22};
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);//sorting array using selection sort
System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
}
}
OUTPUT
10. (c) INSERTION SORT

AIM:

ALGORITHM:

SOURCE CODE:

public class InsertionSort{


public static void insertionSort(int array[])
{
int n = array.length;
for (int j = 1; j < n; j++)
{
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) )
{
array [i+1] = array [i]; i--;
}
array[i+1] = key;
}
}
public static void main(String a[])
{
int[] arr1 = {9,14,3,2,43,11,58,22
};
System.out.println("Before Insertion Sort");
for(int i:arr1)
{
System.out.print(i+" ");
}
System.out.println();
insertionSort(arr1);//sorting array using insertion sort
System.out.println("After Insertion Sort");
for(int i:arr1)
{
System.out.print(i+" ");
}
}
}
OUTPUT
10. (d) RADIX SORT

AIM:

ALGORITHM:

SOURCE CODE:

import java.util.Scanner;
public class RadixSort{
public static void main(String[] args)
{
int i;
Scanner sc = new Scanner(System.in);
int[] a = {90,23,101,45,65,23,67,89,34,23};
radix_sort(a);
System.out.println("\n The sorted array is: \n");
for(i=0;i<10;i++)
System.out.println(a[i]);
}
static int largest(int a[])
int larger=a[0], i;
for(i=1;i<10;i++)
{
if(a[i]>larger)
larger = a[i];
}
return larger;
}
static void radix_sort(int a[])
{
int bucket[][]=new int[10][10];
int bucket_count[]=new int[10];
int i, j, k, remainder, NOP=0, divisor=1, larger, pass;
larger = largest(a);
while(larger>0)
{
NOP++;
larger/=10;
}
for(pass=0;pass<NOP;pass++) // Initialize the buckets
{
for(i=0;i<10;i++)
bucket_count[i]=0;
for(i=0;i<10;i++) {
remainder = (a[i]/divisor)%10;
bucket[remainder][bucket_count[remainder]] = a[i];
bucket_count[remainder] += 1;
}
i=0;
for(k=0;k<10;k++)
{
for(j=0;j<bucket_count[k];j++)
{
a[i] = bucket[k][j];
i++;
}
}
divisor *= 10;
}
}
}

OUTPUT

You might also like