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

Data structure lab programs

The document outlines a series of experiments related to data structures and algorithms implemented in Java, including stack, quick sort, merge sort, splay tree, binary tree, minimal spanning tree using Prim's algorithm, and breadth-first search. Each experiment includes an aim, algorithm steps, and corresponding Java program code. The document serves as a practical guide for understanding and implementing various fundamental data structures and algorithms.

Uploaded by

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

Data structure lab programs

The document outlines a series of experiments related to data structures and algorithms implemented in Java, including stack, quick sort, merge sort, splay tree, binary tree, minimal spanning tree using Prim's algorithm, and breadth-first search. Each experiment includes an aim, algorithm steps, and corresponding Java program code. The document serves as a practical guide for understanding and implementing various fundamental data structures and algorithms.

Uploaded by

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

INDEX

PAGE
S.NO DATE NAME OF THE EXPERIMENT SIGN
NO

1 IMPLEMENTS USING GENERIC


CLASS, THE STACK.

2 IMPLEMENTS THE QUICK SORT


METHOD.

3 IMPLEMENT THE MERGE SORT


METHOD.

4 USES FUNCTIONS TO CREATING A


SPLAYTREE.

5 CREATING A BINARY TREE OF


INTEGERS

6 FIND THE MINIMAL SPANNING TREE


OF A GRAPH USING THE PRIM’S
ALGORITHM

7 BREADTH FIRST SEARCH

IMPLEMENT THE SHELL SORT


8
METHOD

9 IMPLEMENTS USING GENERIC


CLASS, THE QUEUE

10 DOUBLY LINKED LIST

11 SINGLY LINKED LIST

12 IMPLEMENT A SHORTEST PATH


USING FORD’S ALGORITHM
13 IMPLEMENTING AVL TREE

14 IMPLEMENT A KRUSKAL’S
ALGORITHM

15 IMPLEMENT A GRAPH TRAVERSING


ALGORITHM
EX.NO. 1
DATE:
IMPLEMENTS USING JAVA GENERIC CLASS, THE
STACK

AIM
To write a Java program to implement using java generic class, the stack.

ALGORITHM

Step 1: Start the program


Step 2: A pointer call top is used to keep stack of the top element in the
stack
Step 3: When is rising the stack we set its value to -1 so that we can check
If the stack if empty by comparing top==-1
Step 4: On pushing an element we increase the value of the top and place
New element in the position pointed by the top
Step 5: On popping and element, we return the element pointed as the top
and reduce its value
Step 6: Before pushing we check of the stock is already full
Step 7: Before popping we check if the stack is already empty
Step 8: Stop the execution
1.Stack
PROGRAM:

importjava.util.*;
class stack
{
static final int max=1000;
int top;
int a[]=new int[max];
booleanisEmpty()
{
return(top<0);
}
stack()
{
top=-1;
}
boolean push(int x)
{
if(top>=max-1)
{
System.out.println("stack overflow");
return false;
}
else
{
a[++top]=x;
System.out.println(x+"pushed into stack");
return true;
}
}
int pop()
{
if(top<0)
{
System.out.println("stack underflow");
return 0;
}
else
{
int x=a[top--];
return x;
}
}
int peek()
{
if(top<0)
{
System.out.println("stack underflow");
return 0;
}
else
{
int x=a[top];
return x;
}
}
void print()
{
for(int i=top;i>-1;i--)
{
System.out.println(" "+a[i]);
}
}
public static void main(String args[])
{
stack s=new stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.pop()+"popped from stack");
System.out.println("top element is:"+s.peek());
System.out.println("element present in stack:");
s.print();
}
}
Output:

10pushed into stack


20pushed into stack
30pushed into stack
30popped from stack
top element is:20
element present in stack:
20
10
EX.NO. 2
DATE:

IMPLEMENTS THE QUICK SORT METHOD.

AIM
To write a program that implement the quick sort method.

ALGORITHM

Step 1: Start the program

Step 2: An array is divided into sub arrays by selecting the pivot element

Step 3: While dividing the array pivot element should be position is such a way
that element less than pivot (or) keep on the left side and elements than
better pivot or on the right side of the pivot
Step 4: The left and right some arrays or also divided using the same approach
this process continue until such sub array a contains single element
Step 5: This is at the point array element are already sorted finally element or
combined the formula sorted
Step 6: Stop the program
2.Quick Sort
PROGRAM:

import java.io.*;
class quicksort
{
int partition(intarr[],intlow,int high)
{
int pivot=arr[high];
int i=(low-1);
for(int j=low;j<high;j++)
{
if(arr[j]<=pivot)
{
i++;
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
int temp=arr[i+1];
arr[i+1]=arr[high];
arr[high]=temp;
return i+1;
}
void sort(intarr[],intlow,int high)
{
if(low<high)
{
int pi=partition(arr,low,high);
sort(arr,low,pi-1);
sort(arr,pi+1,high);
}
}
static void printarray(intarr[])
{
int n=arr.length;
for(int i=0;i<n;i++)
System.out.println(arr[i]+"");
System.out.println();
}
public static void main(String args[])
{
int[]arr={10,7,8,9,1,5};
int n=arr.length;
quicksortob=new quicksort();
ob.sort(arr,0,n-1);
System.out.println("sorted array:");
printarray(arr);
}
}
Output:

sorted array:
1
5
7
8
9
10
EXP. NO.3
DATE:
IMPLEMENT THE MERGE SORT METHOD

AIM
To write a Java program to implement the merge sort method.

ALGORITHM

Step 1: Start the program


Step 2: Merging into consecutive sub arrays of array create duplicate copies
of Sub arrays to this sorted
Step 3: Maintain current inside of sub arrays and main array
Step 4: Comparing individual elements of sorted sub arrays until we reach end
of one
Step 5: Copy remaining elements from the first array to main sub array
Step 6: Copy the remaining elements of second array to main subarrays
Step 7: At the end of the merge function the subarray is sorted
Step 8: Stop the program
3.Merge Sort
PROGRAM:

classMergeSort
{
void merge(intarr[],intl,intm,int r)
{
int n1=m-l+1;
int n2=r-m;
int L[]=new int[n1];
int R[]=new int[n2];
for(int i=0;i<n1;++i)
L[i]=arr[l+i];
for(int j=0;j<n2;++j)
R[j]=arr[m+1+j];
int i=0,j =0;
int k=l;
while(i<n1&&j<n2)
{
if(L[i]<=R[j])
{
arr[k]=L[i];
i++;
}
else
{
arr[k]=R[j];
j++;
}
k++;
}
while(i<n1)
{
arr[k]=L[i];
i++;
k++;
}
while(j<n2)
{
arr[k]=R[j];
j++;
k++;
}
}
void sort(intarr[],intl,int r)
{
if(l<r)
{
int m=l+(r-l)/2;
sort(arr,l,m);
sort(arr,m+1,r);
merge(arr,l,m,r);
}
}
static void printArray(intarr[])
{
int n=arr.length;
for(int i=0;i<n;++i)
System.out.println(arr[i]+" ");
System.out.println();
}
public static void main(String args[])
{
intarr[]={12,11,13,5,6,7};
System.out.println("Given Array");
printArray(arr);
MergeSortob=new MergeSort();
ob.sort(arr,0,arr.length-1);
System.out.println("\nSorted array");
printArray(arr);
}
}
Output:

Given Array:
12
11
13
5
6
7
Sorted array:
5
6
7
11
12
13
EXP. NO.4
DATE:
FUNCTIONS TO CREATING A SPLAYTREE

AIM
To write a Java program to implement for function to create a splay tree.

ALGORITHM

Step 1: Start the program.


Step 2: Check whether tree is Empty.
Step 3: If tree is Empty then insert the new node as Root node and exit from
the operation.
Step 4: If tree is not Empty then insert the new node as leaf node using Binary
Search tree insertion logic.
Step 5: After insertion, Splay the new node.
Step 6: Stop the program.
4.Splay Tree
PROGRAM:

class Tree
{
static class node
{
int key;
node left, right;
};
static node TreeNode(int key)
{
nodeNode = new node();
Node.key = key;
Node.left = Node.right = null;
return (Node);
}
static node rightRotate(node x)
{
node y = x.left;
x.left = y.right;
y.right = x;
return y;
}
static node leftRotate(node x)
{
node y = x.right;
x.right = y.left;
y.left = x;
return y;
}
static node splay(node root, int key)
{
if (root == null || root.key == key)
return root;
if (root.key> key)
{
if (root.left == null) return root;
if (root.left.key> key)
{
root.left.left = splay(root.left.left, key);
root = rightRotate(root);
}
else if (root.left.key< key)
{
root.left.right = splay(root.left.right, key);
if (root.left.right != null)
root.left = leftRotate(root.left);
}
return (root.left == null) ? root :rightRotate(root);
}
else
{
if (root.right == null) return root;
if (root.right.key> key)
{
root.right.left = splay(root.right.left, key);
if (root.right.left != null)
root.right = rightRotate(root.right);
}
else if (root.right.key< key)
{
root.right.right = splay(root.right.right, key);
root = leftRotate(root);
}
return (root.right == null) ? root :leftRotate(root);
}
}
static node bstSearch(node root, int key)
{
return splay(root, key);
}
static void preOrder(node root)
{
if (root != null)
{
System.out.print(root.key + " ");
preOrder(root.left);
preOrder(root.right);
}
}
public static void main(String args[])
{
node root = TreeNode(100);
root.left = TreeNode(50);
root.right = TreeNode(200);
root.left.left = TreeNode(40);
root.left.left.left = TreeNode(30);
root.left.left.left.left = TreeNode(2);
root = bstSearch(root, 20);
preOrder(root);
}
}
Output:

20 50 30 40 100 200
EXP. NO.5
DATE:
CREATING A BINARY TREE OF INTEGERS

AIM
To write a Java program to creating a binary tree of integers.

ALGORITHM

Step 1: Start the program


Step 2: If root is NULL then create root node return
Step 3: If root exists the compare the data with node data
Step 4: while until insertion position is located
Step 5: If data is greater than node.dat go to right sub tree go to left end while
Step 6: Insert data
Step 7: Stop the program
5.Binary Tree
PROGRAM:

import java.io.*;
importjava.util.*;
classgfg
{
static class Node
{
publicint data;
public Node left,right;
public Node(intval)
{
this.data=val;
this.left=null;
this.right=null;
}
};
static void
PostPreInOrderInFlowRecursive(Noderoot,ArrayList<Integer>pre,ArrayList<Integ>post,ArrayList
<Integer>in)
{
if(root==null)
return;
pre.add(root.data);
PostPreInOrderInFlowRecursive(root.left,pre,post,in);
in.add(root.data);
PostPreInOrderInFlowRecursive(root.right,pre,post,in);
post.add(root.data);
}
public static void main(String args[])
{
Node root=new Node(1);
root.left=new Node(2);
root.right=new Node(3);
root.left.left=new Node(4);
root.left.right=new Node(5);
root.right.left=new Node(6);
root.right.right=new Node(7);
ArrayList<Integer>pre=new ArrayList<>();
ArrayList<Integer>post=new ArrayList<>();
ArrayList<Integer>in=new ArrayList<>();
PostPreInOrderInFlowRecursive(root,pre,post,in);
System.out.println("pre order:");
for(int i:pre)
{
System.out.println(i+"");
}
System.out.println();
System.out.println("post order:");
for(int i:post)
{
System.out.println(i+"");
}
System.out.println();
System.out.println("in order:");
for(int i:in)
{
System.out.println(i+"");
}
}
}
Output:

pre order:
1
2
4
5
3
6
7
post order:
4
5
2
6
7
3
1
in order:
4
2
5
1
6
3
7
EXP. NO.6
DATE:
MINIMAL SPANNING TREE OF A GRAPH USING THE
PRIM’S ALGORITHM.

AIM
To write a program minimal spanning tree of a graph using prim’s algorithm.

ALGORITHM

Step 1: Start the program


Step 2: Initialize the minimum spanning tree with vertex chosen at random
Step 3: Find all the edges that connect the tree to new vertex, find the
minimum and add it to the tree
Step 4: Keep repeating step-3 until we get a minimum spanning tree
Step 5: Stop the program
6.Prim’s Algorithm

PROGRAM:

importjava.util.Arrays;
classPGraph
{
public void prim(int G[][],int V)
{
int INF=9999999;
intno_edge;
boolean[]selected=new boolean[V];
Arrays.fill(selected,false);
no_edge=0;
System.out.println("Edge:Weight");
while(no_edge<V-1)
{
int min=INF;
int x=0;
int y=0;
for(int i=0;i<V;i++)
{
if(selected[i]==true)
{
for(int j=0;j<V;j++)
{
if(!selected[j]&&G[i][j]!=0)
{
if(min>G[i][j])
{
min=G[i][j];
x=i;
y=j;
}
}
}
}
}
System.out.println(x+"-"+y+":"+G[x][y]);
selected[y]=true;
no_edge++;
}}
public static void main(String args[])
{
PGraph g=new PGraph();
int V=5;
int[][]G={{0,7,75,0,0},{9,0,95,19,42},{75,95,0,51,66},{0,19,51,0,31},{0,42,66,3,1,0}
};
g.prim(G,V);
}
}
Output:

Edge:Weight
0-0:0
0-1:7
1-3:19
3-4:31
EXP. NO.7
DATE:
BREADTH FIRST SEARCH

AIM
To write a program for breadth first search.

ALGORITHM

Step 1: Start the program


Step 2: Print program to create a graph and transverse in BFS manner
Step 3: Create an object for class BTS graph
Step 4: Create a graph using function create graph ()
Step 5: Matrix () function is used to find adjacent matrix of the graph
Step 6: Performance breath first search using lef() function
Step 7: Print the breadth first transverse of the graph
Step 8: Stop the program execution
7.Breadth first search

PROGRAM:

importjava.util.Scanner;
public class BFS_Graph
{
finalint TRUE = 1;
finalint FALSE = 0;
finalint MAX = 20;
int[ ][ ] G = new int [MAX] [MAX];
int[] Visit = new int[MAX];
int [] q = new int [MAX];
int n,V1,V2;
intfront,rear;
BFS_Graph()
{
System.out.println("enter number of nodes");
Scanner obj = new Scanner(System.in);
n = Integer.parseInt(obj.nextLine());
for (int i=1; i<=n; i++)
Visit[i]=FALSE;
for(V1=1; V1<=n; V1++)
{
for(V2=1; V2<=n; V2++)
G[V1][V2] = FALSE;
}
front = rear = -1;
}
voidcreateGraph()
{
charans;
System.out.println("enter the edges with vertex no.starting from 1");
do
{
System.out.println("enter the vertices V1 & V2:");
Scanner obj = new Scanner(System.in);
V1 = obj.nextInt();
V2 = obj.nextInt();
if (V1>n || V2>n)
System.out.println("Invalid vertex number ");
else
{
G[V1][V2] = TRUE;
G[V2][V1] = TRUE;
}
System.out.println("want to add more edges (y/n)?");
ans = obj.next().charAt(0);
}
while ((ans== 'y')||(ans== 'Y'));
}
void matrix()
{
System.out.println("adjacency matrix for the graph is");
for (int V1=1; V1<=n; V1++)
{
for(int V2=1; V2<=n; V2++)
System.out.print(G[V1][V2] + " ");
System.out.println();
}
}
voidbfs(int v)
{
int i;
Visit[v] = TRUE;
q[++rear] = v;
while (front != rear)
{
v = q[++front];
System.out.println(v + "");
for(i=1; i<=n; i++)
{
if (G[v][i] == TRUE && Visit[i] == FALSE)
{
q[++rear] = i;
Visit[i] = TRUE;
}
}
}
}
public static void main(String[] args)
{
System.out.println("PROGRAM TO CREATE A GRAPH AND TRAVERSE IN BFS
MANNER");
BFS_Graph g = new BFS_Graph();
g.createGraph();
g.matrix();
System.out.println("breadth first traverse for the above graph is");
g.bfs(1);
}}
Output:

Program to create a graph and traverse in BFS manner


Enter number of nodes
4
Enter the edges with vertex no. starting from 1
Enter the vertices V1&V2:
1
2
Want to add more edges (y/n)?
Y
Enter the vertices V1&V2:
1
3
Want to add more edges (y/n)?
Y
Enter the vertices V1&V2:
1
4
Want to add more edges (y/n)?
Y Enter the vertices V1&V2:
2
3
Want to add more edges (y/n)?
N
Adjacency matrix for the graph is
0111
1010
1100
1000
Breadth first search traverse for the above graph is
1
2
3
4
EXP. NO.8
DATE:
IMPLEMENT THE SHELL SORT METHOD

AIM
To write a Java program that implement shell sort method.

ALGORITHM

Step 1: Start the program


Step 2: Start the given array
Step 3: Use the shell's original sequence (N12,N14....1) as interval in our
algorithm
Step 4: The first loop, if the array size is n,=8 then, the element lying at the
interval of n=4 are composed and swapped if they are not order
Step 5: In the second loop, an interval of [n14=8 / 4=2]is taken and again
element lying are there interval are sorted
Step 6: The same process course on for remaining elements
Step 7: Finally when the intervals is ,[N18=8/8=1] then the elements lying at
the interval of element 1 ace sorted. The array is new shorted
Step 8: Stop the execution
8.Shell Sort

PROGRAM:

classshellsort
{
static void printarray(intarr[])
{
int n=arr.length;
for(int i=0;i<n;i++)
System.out.println(arr[i]+"");
System.out.println();
}
int sort(intarr[])
{
int n=arr.length;
for(int gap=n/2;gap>0;gap/=2)
{
for(int i=gap;i<n;i+=1)
{
int temp=arr[i];
int j;
for(j=i;j>=gap&&arr[j-gap]>temp;j-=gap)
arr[j]=arr[j-gap];
arr[j]=temp;
}
}
return 0;
}
public static void main(String args[])
{
intarr[]={12,34,54,2,3};
System.out.println("array before sorting");
printarray(arr);
shellsortob=new shellsort();
ob.sort(arr);
System.out.println("array after sorting");
printarray(arr);
}
}
Output:

array before sorting:


12
34
54
2
3
array after sorting:
2
3
12
34
54
EX.NO:9
DATE:
IMPLEMENTS USING GENERIC
CLASS, THE QUEUE

AIM
To implement using java generic class ,the queue its operation.

ALGORITHM

Step 1: Check if the queue is full


Step 2: If the queue is full ,produce overflow error and exit
Step 3: If the queue is not full increment near pointer to point the next
empty space
Step 4: Add data element to the queue location, where the near is painting
Step 5: Return success
9.Queue

PROGRAM:

import java.io.*;
import java.util.*;
class queue<T>
{
int front=-1,rear=-1;
ArrayList<T>list=new ArrayList<>();
T front()
{
if(front==-1)
return null;
return list.get(front);
}
T rear()
{
if(rear==-1)
return null;
return list.get(rear);
}
void enqueue(T X)
{
if(this.empty())
{
front=0;
rear=0;
list.add(X);
}
else
{
front++;
if(list.size()>front){
list.add(front,X);
}
else
list.add(X);
}}
void dequeue()
{
if(this.empty())
System.out.println("queue is already empty");
else if(front==rear)
{
front=rear=-1;
}
else
{
rear++;
}}
boolean empty()
{
if(front==-1&&rear==-1)
return true;
return false;
}
public String toString()
{
if(this.empty())
return"";
String ans="";
for(int i=rear;i<front;i++){
ans+=String.valueOf(list.get(i))+"->";
}
ans+=String.valueOf(list.get(front));
return ans;
}
public static void main(String args[])
{
queue<Integer>q=new queue<>();
q.enqueue(10);
q.enqueue(15);
q.enqueue(20);
System.out.println("\n after enqueue of element"+q);
q.dequeue();
System.out.println("after dequeue:\n"+q);
queue<String>q1=new queue<>();
q1.enqueue("coding");
q1.enqueue("ninjas");
System.out.println("after enqueue of element:\n"+q1);
System.out.println("q1 front="+q1.front()+",q1 rear="+q1.rear());
}}
Output:

after enqueue of element10->15->20


after dequeue:
15->20
after enqueue of element:
coding->ninjas
q1 front=ninjas,q1 rear=coding
EX.NO:10
DATE:
DOUBLY LINKED LIST

AIM
To write a Java program to create a doubly linked list implementation.

ALGORITHM

Step 1: Start the program


Step 2: Get the choice from the user
Step 3: If the choice is to add records ,get the data from the user and add
them to the list
Step 4: If the choice is to delete number of records count the items in the
list pivot or on the right side of the pivot
Step 5: If the choice is to display number of records ,count the items in the
list and display
Step 6: If the choice is to search for the item, get the item to be searched
And respond yes if the item is found otherwise no
Step 7: Stop the program
10.Doubly Linked List
PROGRAM:

class Dll
{
node head;
class node
{
int data;
node prev;
node next;
node(int d){data=d;}
}
public void push(int new_data)
{
node new_node=new node(new_data);
new_node.next=head;
new_node.prev=null;
if(head!=null)
head.prev=new_node;
head=new_node;
}
public void insertbefore(node next_node,int new_data)
{
if(next_node==null)
{
System.out.println("the given next node can't be null");
return;
}
node new_node=new node(new_data);
new_node.prev=next_node.prev;
next_node.prev=new_node;
new_node.next=next_node;
if(new_node.prev!=null)
new_node.prev.next=new_node;
else
head=new_node;
}
public void insertafter(node prev_node,int new_data)
{
if(prev_node==null)
{
System.out.println("the given previous node can't be null");
return;
}
node new_node=new node(new_data);
new_node.next=prev_node.next;
prev_node.next=new_node;
new_node.prev=prev_node;
if(new_node.next!=null)
new_node.next.prev=new_node;
}
void append(int new_data)
{
node new_node=new node(new_data);
node last=head;
new_node.next=null;
if(head==null)
{
new_node.prev=null;
head=new_node;
return;
}
while(last.next!=null)
last=last.next;
last.next=new_node;
new_node.prev=last;
}
public void printlist(node node)
{
node last=null;
System.out.println("traversal in forward direction:");
while(node!=null){
System.out.println(node.data+"");
last=node;
node=node.next;
}
System.out.println();
System.out.println("traversal in backward direction:");
while(last!=null){
System.out.println(last.data+"");
last=last.prev;
}}
public static void main(String args[])
{
Dll dll=new Dll();
dll.append(6);
dll.push(7);
dll.push(1);
dll.append(4);
dll.insertafter(dll.head.next,8);
System.out.println("created Dll is:");
dll.printlist(dll.head);
}
}
Output:

created Dll is:


traversal in forward direction:
1
7
8
6
4
traversal in backward direction:
4
6
8
7
1
EX.NO:11
DATE:
SINGLY LINKED LIST
AIM

To write a java program to create a singly linked list implementation.

ALGORITHM

Step 1: Start the program


Step 2: Get the choice from the user
Step 3: If the choice is to add records get the data from the user and add
Them to the list
Step 4: If the choice is to delete number of records count the items in the
List and display
Step 5: If the choice is to display number of records count the items in the
List and display
Step 6: If the choice is to search for the it get the item to be searched and
respond yes if the item is found otherwise no
Step 7: stop the program
11.Singly Linked List
PROGRAM:

import java.io.*;
public class linkedlist
{
node head;
static class node
{
int data;
node next;
node(int d)
{
data=d;
next=null;
}}
public static linkedlist insert(linkedlist list,int data)
{
node new_node=new node(data);
new_node.next=null;
if(list.head==null)
{
list.head=new_node;
new_node.next=null;
}
else{
node last=list.head;
while(last.next!=null)
{
last=last.next;
}
last.next=new_node;
}
return list;
}
public static void printlist(linkedlist list)
{
node currnode=list.head;
System.out.println("\n linked list:");
while(currnode!=null)
{
System.out.println(currnode.data+"");
currnode=currnode.next;
}
System.out.println("\n");
}
public static linkedlist deleteByKey(linkedlist list,int key)
{
node currnode=list.head,prev=null;
if(currnode!=null&&currnode.data==key)
{
list.head=currnode.next;
System.out.println(key+"found and deleted");
return list;
}
while(currnode!=null&&currnode.data!=key)
{
prev=currnode;
currnode=currnode.next;
}
if(currnode!=null)
{
prev.next=currnode.next;
System.out.println(key+"found and delete");
}
if(currnode==null)
{
System.out.println(key+"not found");
}
return list;
}
public static linkedlist deleteAtPosition(linkedlist list,int index)
{
node currnode=list.head,prev=null;
if(index==0 && currnode!=null)
{
list.head=currnode.next;
System.out.println(index+"position element deleted");
return list;
}
int counter=0;
while(currnode!=null)
{
if(counter==index){
prev.next=currnode.next;
System.out.println(index+"position element deleted");
break;
}
else{
prev=currnode;
currnode=currnode.next;
counter++;
}}
if(currnode==null){
System.out.println(index+"position element not found");
}
return list;
}
public static void main(String args[])
{
linkedlist list=new linkedlist();
list=insert(list,1);
list=insert(list,2);
list=insert(list,3);
list=insert(list,4);
list=insert(list,5);
printlist(list);
deleteByKey(list,1);
printlist(list);
deleteByKey(list,4);
printlist(list);
deleteByKey(list,10);
printlist(list);
deleteAtPosition(list,0);
printlist(list);
deleteAtPosition(list,2);
printlist(list);
deleteAtPosition(list,10);
printlist(list);
}
}
Output:

linked list:
1
2
3
4
1found and deleted linked list:
2
3
4
4found and delete linked list:
2
3
10not found linked list:
2
3
0position element deleted linked list:
3
2position element not found linked list:
3
10position element not found linked list:
3
EX.NO:12
DATE:
BELLMAN-FORD’S ALGORITHM

AIM

To write a program find the shortest path using Bellman ford's Algorithm.

ALGORITHM

Step 1: Start the program


Step 2: Let the given source vertex be 0.initialize all distances are
Infinite except the distance to the source itself
Step 3: We get the following distances when all the edges are processed
The first time
Step 4: The first itecation gurantee to give all shortest path which are at
must 1 edge long
Step 5: The second itecation gurantee to give all shortest path with at
at must 2 edge long
Step 6: Stop the program
12.Bellman ford’s Algorithm
PROGRAM:

class GFG
{
static void Bellmanford(int graph[][],int V,int E,int src)
{
int[]dis=new int[V];
for(int i=0;i<V;i++)
dis[i]=Integer.MAX_VALUE;
dis[src]=0;
for(int i=0;i<V-1;i++)
{
for(int j=0;j<E;j++)
{
if(dis[graph[j][0]]!=Integer.MAX_VALUE&&dis[graph[j][0]]+graph[j][2]<dis[graph[j][1]])
dis[graph[j][1]]=dis[graph[j][0]]+graph[j][2];
}}
for(int i=0;i<E;i++)
{
int x=graph[i][0];
int y=graph[i][1];
int weight=graph[i][2];
if(dis[x]!=Integer.MAX_VALUE&&dis[x]+weight<dis[y])
System.out.println("graph contain negative"+"weight cycle");}
System.out.println("vertex distance from source");
for(int i=0;i<V;i++)
System.out.println(i+"\t\t"+dis[i]);
}
public static void main(String args[])
{
int V=5;
int E=8;
int graph[][]={{0,1,-1},{0,2,4},{1,2,3},{1,3,2},{1,4,2},{3,2,5},{3,1,1},{4,3,-2}};
Bellmanford(graph,V,E,0);
}}
Output:

1
vertex distance from source
0 0
1 -1
2 2
3 -1
4
EXP.NO:13
DATE: IMPLEMENTING AVL TREE

AIM

To create a java program to implementing AVL Tree.

ALGORITHM

Step 1: Start the program


Step 2: Write a Java program that you want to compile and run. We have written the
following code in the notepad.
Step 3: To save a Java program press Ctrl + S key and provide the file
name. Remember that the file name must be the same as the class
name followed by the .java extension.
Step 4: If you are writing the Java program as below save it by providing the file name
the Save button. .java press enter key or click on
Step 5: Stop the program
13.IMPLEMENTING AVL TREE
Program:

import java.util.Scanner;
class Node
{
int element; int
h;
Node leftChild;
Node rightChild;
public Node()
{
leftChild = null;
rightChild = null;
element = 0;
h = 0;
}
public Node(int element)
{
leftChild = null; rightChild =
null; this.element = element;
h = 0;
}
}
class ConstructAVLTree
{
private Node rootNode; public
ConstructAVLTree()
{
rootNode = null;
}

public void removeAll()


{
rootNode = null;
}
public boolean checkEmpty()
{
if(rootNode == null
return true;
else
return false;
}
public void insertElement(int element)
{
rootNode = insertElement(element, rootNode);
}
private int getHeight(Node node )
{
return node == null ? -1 : node.h;
}
node
private int getMaxHeight(int leftNodeHeight, int rightNodeHeight)
{
return leftNodeHeight > rightNodeHeight ? leftNodeHeight : rightNodeHeight;
}
private Node insertElement(int element, Node node)
{
if (node == null)
node = new Node(element); else if
(element < node.element)
{
node.leftChild = insertElement( element, node.leftChild );
if( getHeight( node.leftChild ) - getHeight( node.rightChild ) == 2 ) if(
element < node.leftChild.element )
node = rotateWithLeftChild( node ); else
node = doubleWithLeftChild( node );
}
else if( element > node.element )
{
node.rightChild = insertElement( element, node.rightChild );
if( getHeight( node.rightChild ) - getHeight( node.leftChild ) == 2 ) if(
element > node.rightChild.element)
node = rotateWithRightChild( node ); else
node = doubleWithRightChild( node );
}
else
node.h = getMaxHeight( getHeight( node.leftChild ), getHeight( node.rightChild
) ) + 1;
return node;
}
private Node rotateWithLeftChild(Node node2)
{
Node node1 = node2.leftChild;
node2.leftChild = node1.rightChild;
node1.rightChild = node2;
node2.h = getMaxHeight( getHeight( node2.leftChild ), getHeight(
node2.rightChild ) ) + 1;
node1.h = getMaxHeight( getHeight( node1.leftChild ), node2.h ) + 1; return
node1;
}
private Node rotateWithRightChild(Node node1)
{
Node node2 = node1.rightChild;
node1.rightChild = node2.leftChild;
node2.leftChild = node1;
node1.h = getMaxHeight( getHeight( node1.leftChild ), getHeight(
node1.rightChild ) ) + 1;
node2.h = getMaxHeight( getHeight( node2.rightChild ), node1.h ) + 1; return
node2;
}
private Node doubleWithLeftChild(Node node3)
{
node3.leftChild = rotateWithRightChild( node3.leftChild ); return
rotateWithLeftChild( node3 );
}
private Node doubleWithRightChild(Node node1)
{
node1.rightChild = rotateWithLeftChild( node1.rightChild ); return
rotateWithRightChild( node1 );
}
public int getTotalNumberOfNodes()
{
return getTotalNumberOfNodes(rootNode);
}
private int getTotalNumberOfNodes(Node head)
{
private boolean searchElement(Node head, int element)
{
boolean check = false;
while ((head != null) && !check)
{
int headElement = head.element; if
(element < headElement)
head = head.leftChild;
else if (element > headElement) head
= head.rightChild;
else
{
check = true;
break;
}
check = searchElement(head, element);
}
return check;
}
public void inorderTraversal()
{
inorderTraversal(rootNode);
}
private void inorderTraversal(Node head)
{

if (head != null)
{
inorderTraversal(head.leftChild);
System.out.print(head.element+" ");
inorderTraversal(head.rightChild);
}
}
public void preorderTraversal()
{
preorderTraversal(rootNode);
}
private void preorderTraversal(Node head)
{
if (head != null)
{
System.out.print(head.element+" ");
preorderTraversal(head.leftChild);
preorderTraversal(head.rightChild);
}
}
public void postorderTraversal()
{
postorderTraversal(rootNode);
}
private void postorderTraversal(Node head)
{
if (head != null)
{
postorderTraversal(head.leftChild);
postorderTraversal(head.rightChild);
System.out.print(head.element+" ");
}
}
}
public class AVLTreeExample
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); ConstructAVLTree
obj = new ConstructAVLTree();
char choice; do
{
System.out.println("\nSelect an operation:\n");
System.out.println("1. Insert a node");
System.out.println("2. Search a node");
System.out.println("3. Get total number of nodes in AVL Tree");
System.out.println("4. Is AVL Tree empty?"); System.out.println("5.
Remove all nodes from AVL Tree"); System.out.println("6. Display AVL
Tree in Post order"); System.out.println("7. Display AVL Tree in Pre
order"); System.out.println("8. Display AVL Tree in In order");
int ch = sc.nextInt();
switch (ch)
{
case 1 :
System.out.println("Please enter an element to insert in AVL Tree");
obj.insertElement( sc.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to search");
System.out.println(obj.searchElement( sc.nextInt() )); break;
case 3 : System.out.println(obj.getTotalNumberOfNodes());
break;
case 4 : System.out.println(obj.checkEmpty());
break;
case 5 :
obj.removeAll();
System.out.println("\nTree Cleared successfully"); break;
case 6 :
System.out.println("\nDisplay AVL Tree in Post order");
obj.postorderTraversal();
break;
case 7 :
System.out.println("\nDisplay AVL Tree in Pre order");
obj.preorderTraversal();
break;
case 8 :
System.out.println("\nDisplay AVL Tree in In order");
obj.inorderTraversal();
break;
default :
System.out.println("\n ");
break;
}
System.out.println("\nPress 'y' or 'Y' to continue \n"); choice =
sc.next().charAt(0);
} while (choice == 'Y'|| choice == 'y');
}
}
Output:

Selection an operation:
1. Insert a node
2. Search a node
3. Get total number of node in AVL tree
4. Is AVL tree empty?
5. Remove all nodes from AVL tree
6. Display AVL tree in post order
7. Display AVL tree in pre order
8. Display AVL tree in In order
1
Please enter an element to insert in AVL tree
23
EXP.NO:14
DATE: IMPLEMENT A KRUSKAL'S ALGORITHAM

AIM

To create a java program to implementing kruskal's algoritham.

ALGORITHM

Step 1: Start the program


Step 2: Write a kruskal's algoritham Java program that you want to compile and run.
We have written the following code in the notepad.
Step 3: To save a Java program press Ctrl + S key and provide the file
name. Remember that the file name must be the same as the class
name followed by the .java extension.
Step 4: If you are writing the Java program as below save it by providing the file
name the Save button. .java press enter key or click on
Step 5: In the next step, we will compile and run the Java program.
Step 6: Stop the program.
14.KRUSKAL'S ALGORITHAM

Program:

import java.util.*;
class Graph {
class Edge implements Comparable<Edge> {
int src, dest, weight;
public int compareTo(Edge compareEdge) {
return this.weight - compareEdge.weight;
}
};
class subset {
int parent, rank;
};
int vertices, edges;
Edge edge[];
Graph(int v, int e) {
vertices = v;
edges = e;
edge = new Edge[edges];
for (int i = 0; i < e; ++i)
edge[i] = new Edge();
}
int find(subset subsets[], int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
void Union(subset subsets[], int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);

if (subsets[xroot].rank < subsets[yroot].rank)


subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
void KruskalAlgo() {
Edge result[] = new Edge[vertices];
int e = 0;
int i = 0;
for (i = 0; i < vertices; ++i)
result[i] = new Edge();
Arrays.sort(edge);
subset subsets[] = new subset[vertices];
for (i = 0; i < vertices; ++i)
subsets[i] = new subset();
for (int v = 0; v < vertices; ++v) {
subsets[v].parent = v;
subsets[v].rank = 0;

}
i = 0;
while (e < vertices - 1) {
Edge next_edge = new Edge();
next_edge = edge[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
Union(subsets, x, y);
}
}
for (i = 0; i < e; ++i)
System.out.println(result[i].src + " - " + result[i].dest + ": " + result[i].weight);
}
public static void main(String[] args) {
int vertices = 6;
int edges = 8;
Graph G = new Graph(vertices, edges);
G.edge[0].src = 0;
G.edge[0].dest = 1;
G.edge[0].weight = 4;
G.edge[1].src = 0;
G.edge[1].dest = 2;
G.edge[1].weight = 4;
G.edge[2].src = 1;
G.edge[2].dest = 2;
G.edge[2].weight = 2;
G.edge[3].src = 2;
G.edge[3].dest = 3;
G.edge[3].weight = 3;
G.edge[4].src = 2;
G.edge[4].dest = 5;
G.edge[4].weight = 2;
G.edge[5].src = 2;
G.edge[5].dest = 4;
G.edge[5].weight = 4;
G.edge[6].src = 3;
G.edge[6].dest = 4;
G.edge[6].weight = 3;
G.edge[7].src = 5;
G.edge[7].dest = 4;
G.edge[7].weight = 3;
G.KruskalAlgo();
}
}
Output:

1 - 2: 2
2 - 5: 2
2 - 3: 3
3 - 4: 3
0 - 1: 4
EX.NO:15 IMPLEMENT A GRAPH TRAVERSING
DATE: ALGORITHAM

AIM

To create a java program to implementing Graph traversing algoritham.

ALGORITHM

Step 1: Start the program


Step 2: Write a Graph traversing algoritham Java program that you want to compile
and run. We have written the following code in the notepad.
Step 3: To save a Java program press Ctrl + S key and provide the file
name. Remember that the file name must be the same as the class
name followed by the .java extension.
Step 4: If you are writing the Java program as below save it by providing the file\
name the Save button. .java press enter key or click on
Step 5: In the next step, we will compile and run the Java program.
Step 6: Exit the program.
15. TRAVERSING ALGORITHAM
PROGRAM:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List; import
java.util.Queue;
public class BreadthFirstSearchExampleNeighbourList
{
private Queue<Node> queue;
static ArrayList<Node> nodes=new ArrayList<Node>(); static
class Node
{
int data; boolean
visited;
List<Node> neighbours;
Node(int data)
{
this.data=data; this.neighbours=new
ArrayList<>();
}
public void addneighbours(Node neighbourNode)
{
this.neighbours.add(neighbourNode);
}
public List<Node> getNeighbours() {
return neighbours;
}
public void setNeighbours(List<Node> neighbours) {
this.neighbours = neighbours;
}
}
public BreadthFirstSearchExampleNeighbourList()
{
queue = new LinkedList<Node>();
}
public void bfs(Node node)
{
queue.add(node);
node.visited=true;
while (!queue.isEmpty())
{
Node element=queue.remove();
System.out.print(element.data + "t");
List<Node> neighbours=element.getNeighbours(); for (int i
= 0; i < neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited)
{
queue.add(n);
n.visited=true;
}
}
}
}
public static void main(String arg[])
{
Node node40
=new Node(40);
Node node10
=new Node(10);
Node node20
=new Node(20);
Node node30
=new Node(30);
Node node60
=new Node(60);
Node node50
=new Node(50);
Node node70
=new Node(70);
node40.addneighbours(node10);
node40.addneighbours(node20);
node10.addneighbours(node30);
node20.addneighbours(node10);
node20.addneighbours(node30);
node20.addneighbours(node60);
node20.addneighbours(node50);
node30.addneighbours(node60);
node60.addneighbours(node70);
node50.addneighbours(node70);
System.out.println("The BFS traversal of the graph is ");
BreadthFirstSearchExampleNeighbourList bfsExample = new
BreadthFirstSearchExampleNeighbourList();
bfsExample.bfs(node40);
}
}
OUTPUT:

The BFS traversal of the graph is

40t10t20t30t60t50t70t

You might also like