Sei sulla pagina 1di 96

MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111

V.GOPALAKRISHNAN AP/CSE 1



MAHAKAVI BHARATHIYAR COLLEGE OF ENGINEERING AND
TECHNOLOGY

ANNA UNIVERISTY OF TECHNOLOGY THIRUNELVELI

DEPARTMENT OF COMPUTER SCIENCE & ENGG

REGULATION 2013

I-ME CSE (2013-2015)





















CP7111
ADVANCED DATA STRUCTURES LABORATORY
LAB MANUAL






BY
V.GOPALA KRISHNAN,
Assistant Professor



MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 2

Ex.No :1 BREADTH FIRST SEARCH

Date :


AIM:
To write a java program to perform a Breadth First Search in the given graph.

ALGORITHM:

1. Declare all necessary variables and initialize those variables.
2. Get the number of vertices.
3. Store the number of vertices in the variable n.
4. Create a adjacency matrix.Using for loop define edges between the nodes are
present or not.
5. Initialize the queue is empty and m[0]=1 denotes the source node is found.
6. From the source node.traverse through the nodes which have edges from the source
node and move these nodes to found not handle queue.
7. Repeat this process untill all nodes are visited.
8. Finally print order of accessed nodes.















MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 3

PROGRAM:
import java.io.*;
class bfs
{
public static void main(String args[])throws IOException
{
int i,n,j,k;
System.out.println("No of vertices:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
int q[]=new int[10];
int m[]=new int[10];
int a[][]=new int[10][10];
for(i=0;i<n;i++)
{
m[i]=0;
}
System.out.println("\n Enter 1 if edge is present,0 if not");
for(i=0;i<n;i++)
{
System.out.println("\n");
for(j=i;j<n;j++)
{
System.out.println("Edge between"+(i+1)+"and"+(j+1)+":");
a[i][j]=Integer.parseInt(br.readLine());
a[j][i]=a[i][j];
}
a[i][i]=0;
}
System.out.println("\n Order of accessed nodes:\n");
q[0]=0;
m[0]=1;
int u;
int node=1;
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 4

int beg1=1;
int beg=0;
while(node>0)
{
u=q[beg];
beg++;
System.out.println(""+(u+1));
node--;
for(j=0;j<n;j++)
{
if(a[u][j]==1)
{
if(m[j]==0)
{
m[j]=1;
q[beg1]=j;
node++;
beg1++;
}
}
}
}
}
}

OUTPUT :
F:\ds>javac bfs.java
F:\ds>java bfs
Number of vertices: 6
Enter 1 if edge is present, 0 if not
Edges between 1 and 1: 0
1 and 2: 1
1 and 3: 1
1 and 4: 1
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 5

1 and 5: 0
1 and 6: 0
Edges between 2 and 2: 0
2 and 3: 1
2 and 4: 0
2 and 5: 1
2 and 6: 0
Edges between 3 and 3: 0
3 and 4: 1
3 and 5: 1
3 and 6: 1
Edges between 4 and 4: 0
4 and 5: 0
4 and 6: 1
Edges between 5 and 3: 0
5 and 4: 0
Edges between 6 and 6: 0

Order of accessed nodes: 1
2
3
4
5
6













MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 6









































RESULT:
Thus the java program for performing breadth first search algorithm has been executed
successfully and the output is verified.





MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 7

Ex.No :2 DEPTH FIRST SEARCH

Date :

AIM:
To write a java program to perform a Depth First Search in the given graph.
ALGORITHM:
1.Get the number of vertices.
2.To construct edges of graph get 1if edge is present else 0 and repeat the same for all the
vertices of the graph.
3.Store edges in adjacency matrix a[][] and traverse from source node.
4.Initially store m[] with zero .since nodes in graph are not visited. if visited make m[] as
one.
5.To access the order of nodes, for each node check the node is visited or not using m[].
6. In dfs() method ,node visited is marked as one,m[]=1.next node j is traversed by
checking the condition that edge between i and j is present using adjacency matrix a[][]=1 and next
node to be traversed is not visited, m[]=0.
7.The above step is repeated for all the nodes in the graph.
8.The order of accessed node is ouputed.




















MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 8

PROGRAM:
import java.io.*;
class dfs
{
static void dfs(int a[][], int m[], int i, int n)
{
int j;
System.out.println("\t" + (i+1));
m[i] = 1;
for(j=0; j<n; j++)
if(a[i][j]==1 && m[j]==0)
dfs(a,m,j,n);
}

public static void main(String args[]) throws IOException
{
int n, i, j;
System.out.println("No. of vertices : ");
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
n =Integer.parseInt(br.readLine());
int m[]= new int[n];
int a[][] = new int[n][n];
for (i=0; i<n; i++)
{
m[i] = 0;
}
System.out.println("\n\nEnter 1 if edge is present, 0 if not");
for (i=0; i<n; i++)
{
System.out.println("\n");
for (j=i; j<n; j++)
{
System.out.println("Edge between " + (i+1) + " and " + (j+1)+ " : ");
a[i][j] =Integer.parseInt(br.readLine());
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 9

a[j][i]=a[i][j];
}
a[i][i] = 0;
}
System.out.println("\nOrder of accessed nodes : \n");
for (i=0; i<n; i++)
if (m[i]==0)
dfs(a,m,i,n);
}
}
OUTPUT :
F:\ds>javac dfs.java
F:\ds>java dfs
Number of vertices: 6
Enter 1 if edge is present, 0 if not
Edges between 1 and 1: 0
1 and 2: 1
1 and 3: 1
1 and 4: 1
1 and 5: 0
1 and 6: 0
Edges between 2 and 2: 0
2 and 3: 1
2 and 4: 0
2 and 5: 1
2 and 6: 0
Edges between 3 and 3: 0
3 and 4: 1
3 and 5: 1
3 and 6: 1
Edges between 4 and 4: 0
4 and 5: 0
4 and 6: 1
Edges between 5 and 3: 0
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 10

5 and 4: 0
Edges between 6 and 6: 0

Order of accessed nodes: 1
2
3
4
6
5



































MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 11








































RESULT:
Thus the java program for performing depth first search algorithm has been executed successfully
and the output is verified.



MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 12

Ex.No :3 NETWORKFLOW PROBLEM

Date :


AIM:

To write a java program to find Maxflow and Mincut in the given network.

ALGORITHM:

1. Declare all the necessary variables and initialize those variables.
2. Get the number of nodes and graph matrix.
3. Get the source and sink of the graph and store it in the variable source and sink
respectively.
4. Create a object for the class NetworkFlowProb and access the method networkflow.
5. In this get the copy of the graph matrix and store it in residual graph two dimensional
array.
6. Call bfs(),in this find a path from s t destination.
7. Then find the minimum capacity of the find path and also find the augmentation
capacity.
8. Create two arrays that is reachable and unreachable.Using this create a cutest and
add the pairs whose having the capacity zero.
9. Call printcutset(),using this print the mincut in the given graph.

















MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 13

PROGRAM:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;

public class NetworkFlowProb
{
private int[] parent;
private Queue<Integer> queue;
private int numberOfVertices;
private boolean[] visited;
private Set<Pair> cutSet;
private ArrayList<Integer> reachable;
private ArrayList<Integer> unreachable;

public NetworkFlowProb (int numberOfVertices)
{
this.numberOfVertices = numberOfVertices;
this.queue = new LinkedList<Integer>();
parent = new int[numberOfVertices + 1];
visited = new boolean[numberOfVertices + 1];
cutSet = new HashSet<Pair>();
reachable = new ArrayList<Integer>();
unreachable = new ArrayList<Integer>();
}

public boolean bfs (int source, int goal, int graph[][])
{
boolean pathFound = false;
int destination, element;
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 14

for (int vertex = 1; vertex <= numberOfVertices; vertex++)
{
parent[vertex] = -1;
visited[vertex] = false;
}
queue.add(source);
parent[source] = -1;
visited[source] = true;

while (!queue.isEmpty())
{
element = queue.remove();
destination = 1;
while (destination <= numberOfVertices)
{
if (graph[element][destination] > 0 && !visited[destination])
{
parent[destination] = element;
queue.add(destination);
visited[destination] = true;
}
destination++;
}
}

if (visited[goal])
{
pathFound = true;
}
return pathFound;
}

public int networkFlow (int graph[][], int source, int destination)
{
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 15

int u, v;
int maxFlow = 0;
int pathFlow;
int[][] residualGraph = new int[numberOfVertices + 1][numberOfVertices + 1];

for (int sourceVertex = 1; sourceVertex <= numberOfVertices; sourceVertex++)
{
for (int destinationVertex = 1; destinationVertex <= numberOfVertices;
destinationVertex++)
{
residualGraph[sourceVertex][destinationVertex] =
graph[sourceVertex][destinationVertex];
}
}

/*max flow*/
while (bfs(source, destination, residualGraph))
{
pathFlow = Integer.MAX_VALUE;
for (v = destination; v != source; v = parent[v])
{
u = parent[v];
pathFlow = Math.min(pathFlow, residualGraph[u][v]);
}
for (v = destination; v != source; v = parent[v])
{
u = parent[v];
residualGraph[u][v] -= pathFlow;
residualGraph[v][u] += pathFlow;
}
maxFlow += pathFlow;
}

/*calculate the cut set*/
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 16

for (int vertex = 1; vertex <= numberOfVertices; vertex++)
{
if (bfs(source, vertex, residualGraph))
{
reachable.add(vertex);
}
else
{
unreachable.add(vertex);
}
}
for (int i = 0; i < reachable.size(); i++)
{
for (int j = 0; j < unreachable.size(); j++)
{
if (graph[reachable.get(i)][unreachable.get(j)] > 0)
{
cutSet.add (new Pair(reachable.get(i), unreachable.get(j)));
}
}
}
return maxFlow;
}

public void printCutSet ()
{
Iterator<Pair> iterator = cutSet.iterator();
while (iterator.hasNext())
{
Pair pair = iterator.next();
System.out.println(pair.source + "-" + pair.destination);
}
}

MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 17

public static void main (String...arg)
{
int[][] graph;
int numberOfNodes;
int source;
int sink;
int maxFlow;

Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of nodes");
numberOfNodes = scanner.nextInt();
graph = new int[numberOfNodes + 1][numberOfNodes + 1];

System.out.println("Enter the graph matrix");
for (int sourceVertex = 1; sourceVertex <= numberOfNodes; sourceVertex++)
{
for (int destinationVertex = 1; destinationVertex <= numberOfNodes;
destinationVertex++)
{
graph[sourceVertex][destinationVertex] = scanner.nextInt();
}
}
System.out.println("Enter the source of the graph");
source= scanner.nextInt();

System.out.println("Enter the sink of the graph");
sink = scanner.nextInt();

NetworkFlowProb networkFlowProb = new NetworkFlowProb(numberOfNodes);
maxFlow = networkFlowProb.networkFlow(graph, source, sink);

System.out.println("The Max flow in the graph is " + maxFlow);
System.out.println("The Minimum Cut Set in the Graph is ");
networkFlowProb.printCutSet();
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 18

scanner.close();
}
}

class Pair
{
public int source;
public int destination;

public Pair(int source, int destination)
{
this.source = source;
this.destination = destination;
}

public Pair()
{
}
}
OUTPUT :
F:\ds>javac NetworkFlowProb.java
F:\ds>java NetworkFlowProb
Enter the number of nodes
6
Enter the graph matrix
0 16 13 0 0 0
0 0 10 12 0 0
0 4 0 0 14 0
0 0 9 0 0 20
0 0 0 7 0 4
0 0 0 0 0 0
Enter the source of the graph
1
Enter the sink of the graph
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 19

6
The Max flow in the graph is 23
The Minimum Cut Set in the Graph is
2-4
5-6
5-4



































MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 20












































RESULT:

Thus the java program to find maxflow and mincut in the given network has been executed
successfully and the output is verified.



MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 21

Ex.No :4 DIJIKSTRAS ALGORITHM

Date :


AIM:

To write a java program to find the shortest path from source to all nodes using dijikstra's
algorithm in the given graph.

ALGORITHM:

1. Declare all necessary variables and initialize those variables.
2. Get the number of vertices and adjacency matrix.
3. Get the source node and store it in source variable.
4. Create a object for the class DijikstraQueue to access the method dijikstra-algorithm.
5. In this method get the copy of the adjacency matrix. Add the source into the queue.
6. Access getNodewithMinimumDistanceFromQueue,in this get the minimum capacity
vertice and add it to the settle set.
7. Keeping the distance of the node,handle the neighbours of the source and add them to
the queue.After handling the source,remove it from queue.
8. Again handle the nodes that are in queue as the same steps that before we performed.
9. While queue is empty stop the process and then we get the shortest path.
10. Finally, the shortest path from source to each other node is retutn.



















MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 22

PROGRAM:

import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
public class DijkstraQueue
{
private int distances[];
private Queue<Integer> queue;
private Set<Integer> settled;
private int number_of_nodes;
private int adjacencyMatrix[][];

public DijkstraQueue(int number_of_nodes)
{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
settled = new HashSet<Integer>();
queue = new LinkedList<Integer>();
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
}

public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];

for (int i = 1; i <= number_of_nodes; i++)
{
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 23

distances[i] = Integer.MAX_VALUE;
}

queue.add(source);
distances[source] = 0;

while (!queue.isEmpty())
{
evaluationNode = getNodeWithMinimumDistanceFromQueue();
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}
}

private int getNodeWithMinimumDistanceFromQueue()
{
int min ;
int node = 0;
Iterator<Integer> iterator = queue.iterator();
node = iterator.next();
min = distances[node];

for (int i = 1; i <= distances.length; i++)
{
if (queue.contains(i))
{
if (distances[i] <= min)
{
min = distances[i];
node = i;
}
}
}
queue.remove(node);
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 24

return node;
}

private void evaluateNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;

for (int destinationNode = 1; destinationNode <= number_of_nodes;
destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode] !=
Integer.MAX_VALUE)
{
edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
}
queue.add(destinationNode);
}
}
}
}

public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
Scanner scan = new Scanner(System.in);
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 25


try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];

System.out.println("Enter the Weighted Matrix for the graph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}

System.out.println("Enter the source ");
source = scan.nextInt();
DijkstraQueue dijkstrasQueue = new DijkstraQueue(number_of_vertices);
dijkstrasQueue.dijkstra_algorithm(adjacency_matrix, source);

System.out.println("The Shorted Path to all nodes are ");
for (int i = 1; i <= dijkstrasQueue.distances.length - 1; i++)
{
System.out.println(source + " to " + i + " is " + dijkstrasQueue.distances[i]);
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 26

}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}
OUTPUT :
F:\ds>javac DijikstraQueue.java
F:\ds>java DijikstraQueue
Enter the number of vertices
5
Enter the Weighted Matrix for the graph
0 7 0 0 2
0 0 1 0 2
0 0 0 4 0
0 0 5 0 0
0 3 8 5 0
Enter the source
1
The Shorted Path to all nodes are
1 to 1 is 0
1 to 2 is 5
1 to 3 is 6
1 to 4 is 7
1 to 5 is 2







MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 27












































RESULT:

Thus the java program to find shortest path from source to all nodes using dijikstras
algorithm in the given graph has been executed successfully and the output is verified.



MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 28

Ex.No :5 TRAVELLING SALESPERSON PROBLEM

Date :


AIM:

To write a java program to find the shortest path and minimum cost for travelling
salesperson problem.

ALGORITHM:

1. Declare all necessary variables and initialize those variables.
2. Create a object for the class TSP.
3. Get the number of nodes and weight of each edges.
4. The eval() method declares and initializes the dummyset array.
5. The cost() method finds the final cost by finding the cost of each path.
6. The constructor()method finds the path in terms of tour from the source node and
again it reaches the source.
7. From among all the tour paths the one with minimum cost is selected as the best
path.
8. Using display() method the tour path is return along with final cost as the result of
the travelling sales person problem.




















MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 29

PROGRAM:
import java.util.*;
import java.text.*;
class TSP
{
int weight[][],n,tour[],finalCost;
final int INF=1000;
public TSP()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no. of nodes:=>");
n=s.nextInt();
weight=new int[n][n];
tour=new int[n-1];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j)
{
System.out.print("Enter weight of "+(i+1)+" to "+(j+1)+":=>");
weight[i][j]=s.nextInt();
}
}
}
System.out.println();
System.out.println("Starting node assumed to be node 1.");
eval();
}
public int COST(int currentNode,int inputSet[],int setSize)
{
if(setSize==0)
return weight[currentNode][0];
int min=INF,minindex=0;
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 30

int setToBePassedOnToNextCallOfCOST[]=new int[n-1];
for(int i=0;i<setSize;i++)
{
int k=0;//initialise new set
for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
int temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
{
min=weight[currentNode][inputSet[i]]+temp;
minindex=inputSet[i];
}
}
return min;
}
public int MIN(int currentNode,int inputSet[],int setSize)
{
if(setSize==0)
return weight[currentNode][0];
int min=INF,minindex=0;
int setToBePassedOnToNextCallOfCOST[]=new int[n-1];
for(int i=0;i<setSize;i++)//considers each node of inputSet
{
int k=0;
for(int j=0;j<setSize;j++)
{
if(inputSet[i]!=inputSet[j])
setToBePassedOnToNextCallOfCOST[k++]=inputSet[j];
}
int temp=COST(inputSet[i],setToBePassedOnToNextCallOfCOST,setSize-1);
if((weight[currentNode][inputSet[i]]+temp) < min)
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 31

{
min=weight[currentNode][inputSet[i]]+temp;
minindex=inputSet[i];
}
}
return minindex;
}
public void eval()
{
int dummySet[]=new int[n-1];
for(int i=1;i<n;i++)
dummySet[i-1]=i;
finalCost=COST(0,dummySet,n-1);
constructTour();
}
public void constructTour()
{
int previousSet[]=new int[n-1];
int nextSet[]=new int[n-2]; for(int i=1;i<n;i++)
previousSet[i-1]=i;
int setSize=n-1;
tour[0]=MIN(0,previousSet,setSize);
for(int i=1;i<n-1;i++)
{
int k=0;
for(int j=0;j<setSize;j++)
{
if(tour[i-1]!=previousSet[j])
nextSet[k++]=previousSet[j];
}
--setSize;
tour[i]=MIN(tour[i-1],nextSet,setSize);
for(int j=0;j<setSize;j++)
previousSet[j]=nextSet[j];
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 32

}
display();
}
public void display()
{
System.out.println();
System.out.print("The tour is 1-");
for(int i=0;i<n-1;i++)
System.out.print((tour[i]+1)+"-");
System.out.print("1");
System.out.println();
System.out.println("The final cost is "+finalCost);
}
}
class TSPExp
{
public static void main(String args[])
{
TSP obj=new TSP();
}
}
OUTPUT :
F:\ds>javac TSPExp.java
F:\ds>java TSPExp
Enter number of nodes: 4
Enter weight of 1 to 2:5
Enter weight of 1 to 3:3
Enter weight of 1 to 4:14
Enter weight of 2 to 1:6
Enter weight of 2 to 3:5
Enter weight of 2 to 4:60
Enter weight of 3 to 1:2
Enter weight of 3 to 2:1
Enter weight of 3 to 4:7
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 33

Enter weight of 4 to 1:3
Enter weight of 4 to 2:32
Enter weight of 4 to 3:8

Starting node assumed to be node 1
The tour is 1-2-3-4-1
The final cost is 20






































MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 34












































RESULT:

Thus the java program to find the shortest path and minimum cost for travelling
salesperson problem has been executed successfully and the output is verified.



MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 35

Ex.No :6 N -QUEENS PROBLEM

Date :


AIM:

To write a java program to place the N number of Queens in a N*N chess board.

ALGORITHM:

1. Declare all necessary variables and initialize those variables.
2. Get the number of Queens and store it in the variable N.
3. Call enumerate() method and create array a and initialize it.
4. By using the method overloading concept,place the queens one by one.
5. Then by using isconsistent method to check that no two queens should be placed in the
diagonal or in same row or column.
6. Place the queens in the board by satisfying the conditions and mark the remaining place
as *.
7. Finally the output will display all the possible ways to place the queens in chess board.

























MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 36

PROGRAM:
import java.util.*;
public class Queens
{
public static boolean isConsistent(int[] q, int n)
{
for (int i = 0; i < n; i++)
{
if (q[i] == q[n]) return false; // same column
if ((q[i] - q[n]) == (n - i)) return false; // same major diagonal
if ((q[n] - q[i]) == (n - i)) return false; // same minor diagonal
}
return true;
}
public static void printQueens(int[] q)
{
int N = q.length;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (q[i] == j) System.out.print("Q ");
else System.out.print("* ");
}
System.out.println();
}
System.out.println();
}
public static void enumerate(int N)
{
int[] a = new int[N];
enumerate(a, 0);
}
public static void enumerate(int[] q, int n)
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 37

{
int N = q.length;
if (n == N) printQueens(q);
else
{
for (int i = 0; i < N; i++)
{
q[n] = i;
if (isConsistent(q, n)) enumerate(q, n+1);
}
}
}
public static void main(String args[])
{
Scanner S=new Scanner(System.in);
System.out.print("Enter no. of Queens: ");
int N = S.nextInt();
enumerate(N);
}
}
OUTPUT :
F:\ds>javac Queens.java
F:\ds>java Queens
Enter number of Queens: 4

*Q**
***Q
Q***
**Q*

**Q*
Q***
***Q
*Q**
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 38






































RESULT:

Thus the java program to place the N number of queens in a N*N chess board has been
executed successfully and the output is verified.



MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 39

Ex.No :7 GRAPH COLORING

Date :


AIM:

To write a java program to implement graph coloring using recursive backtracking with the
given number of colors.

ALGORITHM:

1. Get the number of vertices and store it in the variable n.
2. Create adjacency matrix,using for loop defines edges between the nodes are present or not.
3. Get the number of colors available and store it in the variable m.
4. mcolouring() method calls another method nextvalue().
5. This method checks the next node value, here nodes are arranged as per the number of
colors available.
6. No two nodes have the same color nearly.
7. For n number of nodes the solution of the graph coloring is displayed.
8. If no solutions are present for the given input then it displays no possible solutions.
























MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 40

PROGRAM:
import java.io.*;
public class GraphColoring
{
static int [][] G;
static int [] x;
static int n, m;
static boolean found = false;

public static BufferedReader br =new BufferedReader(new
InputStreamReader(System.in));

public static void main(String[] args) throws IOException
{
System.out.println("\t\t\t\tGRAPH COLORING");

System.out.print("\nEnter the number of the vertices: ");
n = Integer.parseInt(br.readLine());

G = new int[n+1][n+1];
x = new int[n+1];

System.out.print("\nIf edge between the following vertices enter 1 else 0:\n");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
if((i!=j)&&(i<j))
{
System.out.print(i+" and "+j+": ");
G[j][i]=G[i][j] = Integer.parseInt(br.readLine());
}
if(i==j)
G[i][j]=0;
}
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 41

System.out.print("\nEnter the number of colors available: ");
m = Integer.parseInt(br.readLine());
System.out.println("\nSolution:");
mColoring(1);
if (found == false)
System.out.println("No Solution possible!");
}
static void mColoring(int k)
{
while(true)
{
NextValue(k);
if(x[k] == 0)
return;
if(k == n)
{
for(int i=1; i<=k;i++)
System.out.print(x[i]+" ");
System.out.println();
found = true;
return;
}
else
mColoring(k+1);
}
}

static void NextValue(int k)
{
int j;
while(true)
{
x[k] = (x[k]+1)%(m+1);
if(x[k]==0)
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 42

return;
for(j=1; j<=n; j++)
if( (G[k][j] != 0) && (x[k] == x[j]) )
break;
if(j == n+1)
return;
}
}
}

OUTPUT :

F:\ds>javac GraphColoring.java
F:\ds>java GraphColoring
Enter the number of vertices : 5
If edge between the following vertices enter 1 else 0
1 and 2: 1
1 and 3: 1
1 and 4: 0
1 and 5: 0
2 and 3: 1
2 and 4: 0
2 and 5: 1
3 and 4: 1
3 and 5: 0
4 and 5:1
Enter the number of colors available:3
Solution:
1 2 3 1 3
1 3 2 1 2
2 1 3 1 2
3 1 2 1 2
3 2 1 2 1


MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 43












































RESULT:
Thus the java program to color the nodes in the graph using recursive backtracking with the
number of colors has been executed successfully and the output is verified.


MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 44

Ex.No :8 QUICKSORT

Date :


AIM:
To write a java program to perform Quicksort using randomized algorithm.
ALGORITHM:
1. Create an object for the class QuickSort.
2. generateRandomNumber() method generates seven input values randomly to be sorted.
3. quicksort() method sorts the input list by finding the 'pivot' element in the list input.
4. This list can be split into two parts and sorted in the arraylist 'less' and 'greater'.
5. concatenate() method gets the 'less','pivot','greater' as inputs and concatenates them and
provide a new sorted list.
6. This new list is the result which is quick sorted.

























MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 45

PROGRAM:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.lang.*;
public class QuickSort
{
public static void main(String[] args)
{
QuickSort app = new QuickSort();
List<Integer> input = app.generateRandomNumbers(7);
System.out.println(input);
System.out.println(app.quicksort(input));
}
private List<Integer> quicksort(List<Integer> input)
{
if(input.size() <= 1)
{
return input;
}
int middle = (int) Math.ceil((double)input.size() / 2);
int pivot = input.get(middle);
List<Integer> less = new ArrayList<Integer>();
List<Integer> greater = new ArrayList<Integer>();
for (int i = 0; i < input.size(); i++)
{
if(input.get(i) <= pivot)
{
if(i == middle)
{
continue;
}
less.add(input.get(i));
}
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 46

Else
{
greater.add(input.get(i));
}
}

return concatenate(quicksort(less), pivot, quicksort(greater));
}

private List<Integer> concatenate(List<Integer> less, int pivot, List<Integer> greater)
{

List<Integer> list = new ArrayList<Integer>();

for (int i = 0; i < less.size(); i++)
{
list.add(less.get(i));
}

list.add(pivot);

for (int i = 0; i < greater.size(); i++) {
list.add(greater.get(i));
}

return list;
}
private List<Integer> generateRandomNumbers(int n)
{
List<Integer> list = new ArrayList<Integer>(n);
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(n * 10));
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 47

}

return list;
}

}
OUTPUT :
F:\ds>javac QuickSort.java
F:\ds>java QuickSort

[58,59,30,25,10,51,53]
[10,25,30,51,53,58,59]































MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 48









































RESULT:
Thus the java program to perform Quicksort using randomized algorithm has been
executed successfully and the output is verified.




MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 49

Ex.No :9 BANKERS ALGORITHM

Date :


AIM:

To write a java program to allocate the resources for processes using bankers algorithm.

ALGORITHM:

1. Get the number of processes and store it in the variable pr.
2. Get the number of resources and store it in the variable res.
3. Each resource each process is currently holding is represented by the allocation matrix and
store it in all[][] which is the two dimensional array.
4. Get the max matrix ,it defines the maximum demand of each process and store it in
max[][] which is the two dimensional array.
5. calculate the need matrix which indicates the remaining resource need of each process it
can be obtained by subtracting the allocation matrix from the max matrix.
6. Each resource the system currently has available is denoted by the availability matrix and
store it in avail[] which is the one dimensional array.
7. For each process the flag is set to -1 then print busy.
8. Allocate the resources for each processes without any deadlock.
9. Flag[] array can be used to store the flag values.
10. Ord[] array can be used to store the order of process.

















MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 50

PROGRAM:

import java.io.*;
class Bankers
{
public static void main(String args[])throws IOException
{
int all[][]=new int[10][10];
int max[][]=new int[10][10];
int need[][]=new int[10][10];
int avail[]=new int[10];
int ord[]=new int[10];
int flags[]=new int[10];
int i,j,pr,res,count=0,flag=0;
DataInputStream dis=new DataInputStream(System.in);
System.out.println(Enter no of processes : );
pr=Integer.parseInt(dis.readLine());
System.out.println(Enter no. of resources : );
res=Integer.parseInt(dis.readLine());
System.out.println(Enter allocation matrix : );
for(i=0;i<pr;i++)
{
for(j=0;j<res;j++)
{
all[i][j]=Integer.parseInt(dis.readLine());
}
}
System.out.println(Enter max matrix : );
for(i=0;i<pr;i++)
{
for(j=0;j<res;j++)
{
max[i][j]=Integer.parseInt(dis.readLine());
need[i][j]=max[i][j]-all[i][j];
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 51

}
}
System.out.println(Enter avail matrix : );
for(j=0;j<res;j++)
{
avail[j]=Integer.parseInt(dis.readLine());
}
for(j=0;j<pr;j++)
{
flags[j]=-1;
System.out.println(Busy);
}
System.out.println(Need matrix : );
for(i=0;i<pr;i++)
{
for(j=0;j<res;j++)
{
System.out.print(need[i][j]+ );
}
System.out.println();
}
int t=0;
while(count<pr)
{
for(i=0;i<pr;i++)
{
if(flags[i]==-1)
{
System.out.print(i =+i+ );
flag=0;
for(j=0;j<res;j++)
{
if(need[i][j]>avail[j])
{
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 52

flag=1;
}
}
System.out.print(flag =+flag+ );
if(flag==0)
{
for(j=0;j<res;j++)
{
avail[j]=avail[j]+all[i][j];
}
count++;
ord[t++]=i;
flags[i]=1;
}
System.out.print(c =+count+ );
for(j=0;j<res;j++)
System.out.print(avail[j]);
System.out.println();
}
}
}
System.out.println(Order);
for(i=0;i<pr;i++)
{
System.out.print(ord[i]+ );
}
}
}
OUTPUT :
F:\ds>javac Bankers.java
F:\ds>java Bankers
Enter no of processes :
5
Enter no. of resources :
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 53

4
Enter allocation matrix :
0
0
1
2
1
0
0
0
1
3
5
4
0
6
3
2
0
0
1
4
Enter max matrix :
0
0
1
2
1
7
5
0
2
3
5
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 54

6
0
6
5
2
0
6
5
6
Enter avail matrix :
1
5
2
0
Busy
Busy
Busy
Busy
Busy
Need matrix :
0 0 0 0
0 7 5 0
1 0 0 2
0 0 2 0
0 6 4 2
i =0 flag =0 c =1 1532
i =1 flag =1 c =1 1532
i =2 flag =0 c =2 2886
i =3 flag =0 c =3 214118
i =4 flag =0 c =4 2141212
i =1 flag =0 c =5 3141212
Order
0 2 3 4 1

MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 55












































RESULT:

Thus the java program to allocate the resources for processes using bankers algorithm has
been executed successfully and the output is verified.




MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 56

Ex. No :10 CONCURRENT LINKEDLIST

Date :


AIM:
To write a java program to perform a concurrent Linked List.

ALGORITHM:
1. Declare all necessary variables and initialise those variables.
2. In CDApp class create a object for the class CDLinkList.
3. Create an object for the class CDApp.
4. Print the menu which has operations like add,view,search,delete,exit.
5. Get the choice that which operation you want to do.
6. Using switch case perform the operation in the menu.
7. Create an object for the class CDDetails,it maintains the details which has enter in the class
CDApp.
8. If we perform one operation then that operation is locked,if we finish that operation then the
lock will be release.
9. In add operation we can add titles and categaries, in view operation we can view the details
in the list.
10. In search operation we can search any titles that already present in the list if the details are
not present then it returns element not found.
11. In delete operation we can remove details in the list.











MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 57

PROGRAM:
CDApp.java
package cd;
import java.util.Scanner;
public class CDApp
{
public static CDLinkList d = new CDLinkList();
public static void main(String[] args) {
final CDApp db = new CDApp();
while (true) {
System.out.println(" MENU ");
System.out.println("1.Add new CD ");
System.out.println("2.View all CDs ");
System.out.println("3.search CD based on title ");
System.out.println("4.Delete CD entry ");
System.out.println("5.Exit");
try {
Scanner sin =new Scanner(System.in);
int choice =sin.nextInt(); //Integer.parseInt(br.readLine());
switch (choice) {
case 1:
System.out.println("Enter CD Title ");
final String title = sin.next();//br.readLine();
System.out.println("Enter CD Category ");
System.out.println("Education ");
System.out.println("Entertainment ");
System.out.println("Games ");
System.out.println("Examinations ");
System.out.println("Soft Skills ");
final String category = sin.next();//Integer.parseInt(br.readLine());
Thread one = new Thread(new Runnable() {
public void run() {
System.out.println("Thread 1 ");
db.addEntry(title, category);
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 58

}
});
Thread two = new Thread(new Runnable() {
public void run() {
System.out.println("Thread 2 ");
db.addEntry(title, category);
}
});
one.start();
one.sleep(1000);
two.start();
break;
case 2:
String cds = db.viewEntries();
System.out.println(cds);
break;
case 3:
System.out.println("Enter CD Title ");
String tit =sin.next();
db.viewEntry(tit);
break;
case 4:
System.out.println("Enter CD Title ");
final String t = sin.next();
Thread three = new Thread(new Runnable() {
public void run() {
System.out.println("Thread 3 ");
db.removeEntry(t);
}
});
Thread four = new Thread(new Runnable() {
public void run() {
System.out.println("Thread 4 ");
db.removeEntry(t);
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 59

}
});
three.start();
four.start();
// db.removeEntry(t);
break;
case 5:
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
}

}
}
public void addEntry(String tit, String cat) {
CDDetails data = new CDDetails(tit, cat);
boolean s = d.find(data);
if (s==true) {
System.out.println("CD already present");
}
else
{
d.add(data);
}
}
public void removeEntry(String tit) {
CDDetails data = new CDDetails(tit);
d.remove(data);
}
public void viewEntry(String tit) {
CDDetails data = new CDDetails(tit);
String cdEntry = d.viewEntry(data);
if (cdEntry.length() > 0) {
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 60

System.out.println("CD found"+cdEntry.length());
System.out.println("Title & category:"+"\n"+ cdEntry);

}
}
public String viewEntries() {
return d.view();
}
}
CDDetails.java
package cd;
public class CDDetails
{
private String cdTitle;
private String cdCatogory;
public CDDetails(String title, String category) {
this.cdTitle = title;
this.cdCatogory = category;
}
public CDDetails(String title) {
this.cdTitle = title;
this.cdCatogory = "";
}
public void setTitle(String title) {
this.cdTitle = title;
}
public void setCategory(String category) {
this.cdCatogory = category;
}
public String getTitle() {
return cdTitle;
}
public String getCategory() {
return cdCatogory;
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 61

}
public int hashCode() {
return cdTitle.hashCode();
}
public boolean equals(Object obj) {
boolean flag = false;
CDDetails cd = (CDDetails) obj;
//equals used by view entry method
if(cd.cdCatogory=="")
{
if (this.cdTitle.equals(cd.cdTitle))
flag = true;
return flag;
}
//equals used by find method
else
{
if (this.cdTitle.equals(cd.cdTitle) && this.cdCatogory.equals(cd.cdCatogory))
flag = true;
return flag;
}
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append( this.cdTitle+"\t");
buffer.append( this.cdCatogory+"\n");
return buffer.toString();
}
}
CDLinkList.java
package cd;
import java.util.concurrent.locks.*;
public class CDLinkList
{
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 62

private ListNode firstNode;
private int size;
private Lock lock = new ReentrantLock();
public class ListNode {
private Object data;
private ListNode next;
public ListNode(Object inputData) {
this.data = inputData;
this.next = null;
}
public Object getData() {
return data;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append( this.data+"\t");
return buffer.toString();
}
public boolean equals(Object obj) {
boolean flag = false;
ListNode ln = (ListNode) obj;
if (this.data.equals(ln.data))
return true;
return flag;
}
}
/* public CDLinkList() {
this.firstNode = null;
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 63

this.size = 0;
}
*/
public Lock getLock() {
return lock;
}
public void setLock(Lock lock) {
this.lock = lock;
}
public void add(Object inputData) {
System.out.println("Lock in insert");
lock.lock();
ListNode curr;
ListNode node = new ListNode(inputData);
if (this.size == 0)
{
this.firstNode = node;
curr = this.firstNode;
}
else
{
curr = this.firstNode;
while (curr.getNext() != null)
{
curr = curr.getNext();
}
curr.setNext(node);
}
this.size++;
lock.unlock();
}
public void remove(Object inputData) {
System.out.println("Lock in remove");
lock.lock();
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 64

ListNode curr;
ListNode prev = null;
ListNode input = new ListNode(inputData);
boolean f=false;
curr = this.firstNode;
if(curr==null)
{
System.out.println("List is empty");
}
else
{
// while(curr!=null)
// {
while (!curr.equals(input)) {
if (curr.getNext() == null)
break;
prev = curr;
curr = curr.getNext();
}
/*if (prev == null)
{
if(curr.equals(input))
{
this.firstNode = curr.getNext();
this.size--;
f=true;
}
else
f=false;
} */
if (prev == null && curr.equals(input))
{
if(curr.getNext()==null)
this.firstNode=null;
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 65

else
this.firstNode = curr.getNext();
this.size--;
f=true;
}
else if (curr.next == null)
{
if(curr.equals(input))
{
prev.next= null;
this.size--;
f=true;
}
else
f=false;
}
else
{
prev.next = curr.getNext();
this.size--;
f=true;
}
// curr=curr.getNext();
// }
}
if(f==true)
System.out.println("Element Deleted");
else if(f==false)
System.out.println("Element not found");
lock.unlock();
}
public String view() {
System.out.println("Lock in view");
lock.lock();
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 66

ListNode currentNode = this.firstNode;
if(currentNode!=null)
{
StringBuffer buffer = new StringBuffer();
System.out.println("Title"+ " " +"Category");
System.out.println("------------------------");
while( currentNode != null )
{
Object dataObject = currentNode.getData();
buffer.append(dataObject);
currentNode = currentNode.getNext();
}
lock.unlock();
return buffer.toString();
}
else
{
StringBuffer buffer1 = new StringBuffer();
buffer1.append("List is empty");
lock.unlock();
return buffer1.toString();
}
}
public String viewEntry(Object inputData) {
System.out.println("Lock in view single entry");
lock.lock();
ListNode curr = this.firstNode;
StringBuffer buffer = new StringBuffer();
ListNode input = new ListNode(inputData);
while( curr != null )
{
while (!curr.equals(input)) {
if (curr.getNext() == null)
break;
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 67

curr = curr.getNext();
}
if (curr.next == null)
{
if(this.size==1 || this.size !=1)
{
if(curr.equals(input))
{
Object dataObject = curr.getData();
buffer.append(dataObject);
}
else
{
System.out.println("Element not found");
}
}
}
else if(curr.next!=null)
{
if(curr.equals(input))
{

Object dataObject = curr.getData();
buffer.append(dataObject);
}
else
{
System.out.println("Element not found");
}
}
curr = curr.getNext();
}
lock.unlock();
return buffer.toString();
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 68

}
public boolean find(Object inputData) {
//lock.lock();
// System.out.println("Lock in view single entry");
ListNode curr = this.firstNode;
boolean flag=false;
ListNode input = new ListNode(inputData);
if(curr==null)
return false;
while (!curr.equals(input)) {
if (curr.getNext() == null)
break;
curr = curr.getNext();
}
if(curr.equals(input))
flag=true;
else
flag=false;
return flag;
}
}
OUTPUT :
init:
deps-jar:
compile-single:
run-single:
MENU
1.Add new CD
2.View all CDs
3.search CD based on title
4.Delete CD entry
5.Exit

1
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 69

Enter CD Title
XXX
Enter CD Category
Education
Entertainment
Games
Examinations
Soft Skills

Education
Thread 1
Lock in insert
MENU
1.Add new CD
2.View all CDs
3.search CD based on title
4.Delete CD entry
5.Exit
Thread 2
CD already present

1
Enter CD Title
ZZZ
Enter CD Category
Education
Entertainment
Games
Examinations
Soft Skills

Entertainment
Thread 1
Lock in insert
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 70

MENU
1.Add new CD
2.View all CDs
3.search CD based on title
4.Delete CD entry
5.Exit
Thread 2
CD already present

2
Lock in view
Title Category
------------------------
XXX Education
ZZZ Entertainment

MENU
1.Add new CD
2.View all CDs
3.search CD based on title
4.Delete CD entry
5.Exit

3
Enter CD Title
XXX
Lock in view single entry
Element not found
CD found14
Title & category:
XXX Education

MENU
1.Add new CD
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 71

2.View all CDs
3.search CD based on title
4.Delete CD entry
5.Exit

4
Enter CD Title
ZZZ
Thread 3
Thread 4
Lock in remove
Element Deleted
MENU
1.Add new CD
2.View all CDs
3.search CD based on title
4.Delete CD entry
5.Exit
Lock in remove
Element not found

5
BUILD SUCCESSFUL (total time: 12 minutes 19 seconds)















MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 72



































RESULT:
Thus the java program to perform a concurrent Linked List has been executed successfully
and the output is verified.





MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 73

Ex.No :11 CONCURRENT STACK

Date :


AIM:
To write a java program to perform concurrent stack.

ALGORITHM:
1. In stack print the options 1.push ,2.pop ,3.view stack element, 4.exit for operations in
stack.Get the option in variable choice and execute using switch case.
2. If choice is 1 executed by threads. if thread1 ,then do push operation by getting an element
and store it in variable x.using run method execute thread 1 and push x into d1.If thread 2
then do pop.
3. If thread 3 then push all the elements in the stack in to d1.
4. Execeptions were catched using catch(InterruptedException e) using print StackTrace
method
5. If choice is 2 then do pop operation and remove the element at the top of the stack put it in
d1.
6. If choice is 3 then view method views the element in d1.
7. If choice is 4 then exit.
8. class StackImp is used to make Backoff with minimum delay and maximum delay.
9. Class Node the element are stored in the variable value .the null value is stored in next
variable
10. The values are returned to the stackappl class.















MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 74

PROGRAM:
Backoff.java
package test;
import java.util.Random;
public class Backoff {
final int minDelay, maxDelay;
int limit;
final Random random;
public Backoff(int min, int max) {
minDelay = min;
maxDelay = max;
limit = minDelay;
random = new Random();
}
public void backoff() throws InterruptedException {
int delay = random.nextInt(limit);
limit = Math.min(maxDelay, 2 * limit);
Thread.sleep(delay);
}
}

Node.java:
package test;
public class Node {
public int value;
public Node next;
public Node()
{
value =0;
next = null;
}
public Node(int val)
{
value = val;
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 75

next = null;
}

}
StackApp.java:
package test;
import java.util.Scanner;
public class StackApp {
static StackImp d1 = new StackImp();
static StackApp d = new StackApp();
public static void main(String[] args) throws InterruptedException {
Scanner sin =new Scanner(System.in);
while (true) {
System.out.println(" MENU ");
System.out.println("1.Push");
System.out.println("2.Pop");
System.out.println("3.View Stack Element");
System.out.println("4.Exit");
int choice =sin.nextInt();
switch (choice) {
case 1:
System.out.println("Enter item:");
final int x=sin.nextInt();
Thread one = new Thread(new Runnable() {
public void run() {
System.out.println("Thread 1 ");
try {
d1.push(x);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 76

Thread two = new Thread(new Runnable() {
public void run() {
System.out.println("Thread 2 ");
try {
//d1.push(x);
d1.pop();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread three = new Thread(new Runnable() {
public void run() {
System.out.println("Thread 3 ");
try {
d1.push(x);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// one.start();
//one.sleep(1000);
two.start();
// three.start();
//d1.push(x);
break;
case 2:
d1.pop();
break;
case 3:
d1.view();
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 77

break;
case 4:
System.exit(0);

}
}
}
}

StackImp.java:
package test;
import java.util.concurrent.atomic.AtomicReference;
public class StackImp {
AtomicReference<Node> top = new AtomicReference<Node>(null);
static final int MIN_DELAY = 1000;
static final int MAX_DELAY = 10000;
Backoff backoff = new Backoff(MIN_DELAY, MAX_DELAY);
public boolean tryPush(Node node){
Node oldTop = top.get();
node.next = oldTop;
return(top.compareAndSet(oldTop, node));
}
public void push(int value) throws InterruptedException {
Node node = new Node(value);
while (true) {
if (tryPush(node)) {
return;
} else {
backoff.backoff();
}
}
}
public Node tryPop()
{
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 78

Node oldTop = top.get();
if (oldTop == null) {
}
Node newTop = oldTop.next;
if (top.compareAndSet(oldTop, newTop)) {
return oldTop;
} else
{
return null;
}
}
public int pop() throws InterruptedException
{
while (true)
{
Node returnNode = tryPop();
if (returnNode != null)
{
return returnNode.value;
} else
{
backoff.backoff();
}
}
}
public void view()
{
Node currentNode = top.get();
if(currentNode!=null)
{
while( currentNode != null )
{
System.out.println(currentNode.value);
currentNode = currentNode.next;
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 79

}
}
else
{
System.out.println("stack is empty");
}
}
}
OUTPUT :
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
1
Enter item:
20
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
Thread 2
1
Enter item:
30
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
Thread 2
1

MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 80

Enter item:
40
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
Thread 2
1
Enter item:
50
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
Thread 2
1
Enter item:
60
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
Thread 2
2
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
3
50
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 81

40
30
20
MENU
1. Push
2. Pop
3. View Stack Element
4. Exit
BUILD SUCCESSFUL (total time : 50 seconds)




































MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 82










































RESULT:

Thus the java program to perform concurrent stack has been executed successfully and the
output is verified.





MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 83

Ex.No :12 CONCURRENT QUEUE

Date :


AIM:
To write a java program to perform a concurrent queue.
ALGORITHM:
1. Initialize the necessary variables.
2. In the empApp class create an object for QueueImp and for MyQueue.
3. In the empApp, perform the switch case with operations like adding and deleting
emp details and viewing them.
4. In the add operation, the threads are used to get the details of employees and add
them to the queue. Similarly, we can perform delete operations by representing any
one of the emp details. In view operation, we can view the details that are entered.
5. The QueueImp object is used to perform Lock and Unlock operation. For this it
requires capacity to pass as a parameter.
6. Also create a class known as ListNode with declarations for data and listnode next.
7. In this the Wake Dequeuers are used to perform lock and to release it after
completing the operation.
8. In MyQueue object, this operator is used to get the emp id, name and the dept. these
details are get in the form of a string.
9. Once the emp detail is deleted, the dequeue thread is displayed and the order of
threads are rearranged and displayed when option 3 is entered.
10. In such a way all the operations are performed as we enter the option.














MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 84

PROGRAM:
empApp.java
package test;
import java.util.Scanner;
public class empApp
{
// public static Map<Integer, String> hm = new HashMap<Integer, String>();
QueueImp eq = new QueueImp(3);
public static void main(String[] args) {
final empApp db = new empApp();
while (true) {
System.out.println(" MENU ");
System.out.println("1.Add emp details");
System.out.println("2.Delete emp detail ");
System.out.println("3.view");
System.out.println("4.Exit");
try {
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sin =new Scanner(System.in);
int choice =sin.nextInt(); //Integer.parseInt(br.readLine());
switch (choice) {
case 1:
Thread one = new Thread(new Runnable() {
public void run() {
try {
db.addEntry();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread two = new Thread(new Runnable() {
public void run() {
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 85

try {
db.addEntry();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread three = new Thread(new Runnable() {
public void run() {
try {
db.addEntry();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread four = new Thread(new Runnable() {
public void run() {
try {
System.out.println("Dequeue thread");
db.removeEntry();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
System.out.println("Thread id:"+one.getId());
one.start();
one.sleep(5000);
System.out.println("Thread id:"+two.getId());
two.start();
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 86

two.sleep(5000);
System.out.println("Thread id:"+three.getId());
three.start();
three.sleep(8000);
System.out.println("Thread id:"+four.getId());
four.start();
break;
case 2:
//db.removeEntry();
Thread five = new Thread(new Runnable() {
public void run() {
try {
db.removeEntry();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

Thread six = new Thread(new Runnable() {
public void run() {
try {
db.addEntry();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread seven = new Thread(new Runnable() {
public void run() {
try {
db.addEntry();
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 87

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
System.out.println("Thread id:"+five.getId());
five.start();
five.sleep(8000);
System.out.println("Thread id:"+six.getId());
six.start();
six.sleep(5000);
System.out.println("Thread id:"+seven.getId());
seven.start();
seven.sleep(5000);
break;
case 3:
String cds = db.viewEntries();
System.out.println(cds);
break;
case 4:
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void addEntry() throws InterruptedException {
Scanner sin =new Scanner(System.in);
System.out.println("Enter emp id ");
final int id=sin.nextInt();
System.out.println("Enter emp name");
final String name = sin.next();//br.readLine();
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 88

System.out.println("Enter emp dept ");
final String dept= sin.next();//Integer.parseInt(br.readLine());
MyQueue data = new MyQueue(name,dept,id);
eq.enq(data);
}
public Object removeEntry()throws InterruptedException {
Object s=eq.deq();
return s;
}
public String viewEntries() {
return eq.view();
}
}
MyQueue.java:
package test;
public class MyQueue
{
private String empName;
private String empDept;
private int id;
public MyQueue(String name, String dept,int id) {
this.id=id;
this.empName = name;
this.empDept = dept;
}
public MyQueue(int id) {
this.id=id;
}
public void setName(String name) {
this.empName = name;
}
public void setDept(String dept) {
this.empDept = dept;
}
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 89

public void setId(int id) {
this.id = id;
}
public String getName() {
return this.empName;
}
public String getDept() {
return this.empDept;
}
public int getId() {
return this.id;
}
/* public boolean equals(Object obj) {
boolean flag = false;
MyQueue m=(MyQueue) obj;
if (this.id.equals(m.id))
flag = true;
return flag;
}*/

public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append( this.id+"\t");
buffer.append( this.empName+"\t");
buffer.append( this.empDept+"\n");
return buffer.toString();
}
}
QueueImp.java:
package test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 90

public class QueueImp {
private ListNode head,tail;
private int capacity;
private Lock enqLock, deqLock;
private Condition notEmptyCondition, notFullCondition;
AtomicInteger size;
public QueueImp(int cap) {
capacity = cap;
head = new ListNode(null);
tail = head;
size = new AtomicInteger(0);
enqLock = new ReentrantLock();
notFullCondition = enqLock.newCondition();
deqLock = new ReentrantLock();
notEmptyCondition = deqLock.newCondition();
}
public class ListNode {
private Object data;
private ListNode next;

public ListNode(Object inputData) {
this.data = inputData;
this.next = null;
}
public Object getData() {
return data;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
public String toString() {
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 91

StringBuffer buffer = new StringBuffer();
buffer.append( this.data+"\t");
return buffer.toString();
}
}
public void enq(Object x) throws InterruptedException {
boolean mustWakeDequeuers = false;
enqLock.lock();
try {
if (size.get() == capacity)
{
// notFullCondition.await();
Thread one = new Thread(new Runnable() {
public void run() {
System.out.println("Call dequeue by thread");
try {
deq();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
one.start();
}
ListNode e = new ListNode(x);
tail.next = tail = e;
if (size.getAndIncrement() == 0)
mustWakeDequeuers = true;
} finally {
enqLock.unlock();
}
if (mustWakeDequeuers) {
deqLock.lock();
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 92

try {
notEmptyCondition.signalAll();
} finally {
deqLock.unlock();
}
}
}
public Object deq() throws InterruptedException {
Object result;
boolean mustWakeEnqueuers = true;
deqLock.lock();
try {
while (size.get() == 0)
notEmptyCondition.await();
result = head.next.data;
head = head.next;
if (size.getAndDecrement() == capacity) {
mustWakeEnqueuers = true;
}
} finally {
deqLock.unlock();
}
if (mustWakeEnqueuers) {
enqLock.lock();
try {
notFullCondition.signalAll();
} finally {
enqLock.unlock();
}
}
return result;
}
public String view()
{
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 93

ListNode currentNode = this.head.next;
if(currentNode!=null)
{
StringBuffer buffer = new StringBuffer();
System.out.println("Id"+ " " +"Name"+ " "+"Dept" );
System.out.println("------------------------");
while( currentNode != null )
{
Object dataObject = currentNode.getData();
buffer.append(dataObject);
currentNode = currentNode.getNext();
}
return buffer.toString();
}
else
{
StringBuffer buffer1 = new StringBuffer();
buffer1.append("Queue is empty");
return buffer1.toString();
}
}
}
OUTPUT :
MENU
1.Add emp details
2. Delete emp detail
3. view
4. Exit
3
Queue is empty
MENU
1.Add emp details
2. Delete emp detail
3. view
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 94

4. Exit
1
Thread id :8
Enter emp id
1
Enter emp name
XXX
Enter emp dept
CSE
Thread id :9
Enter emp id
2
Enter emp name
YYY
Enter emp dept
EEE
Thread id :10
Enter emp id
3
Enter emp name
ZZZ
Enter emp dept
ECE
Thread id :11
MENU
1.Add emp details
2. Delete emp detail
3. view
4. Exit
Dequeue thread
3
Id Name Dept
--------------------------------------
1 XXX CSE
MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 95

2 YYY EEE
3 ZZZ ECE
MENU
1.Add emp details
2. Delete emp detail
3. view
4. Exit
4





































MBCET ME/CSE ADVANCED DATA STRUCTURES LAB CP7111
V.GOPALAKRISHNAN AP/CSE 96








































RESULT:
Thus the java program to perform concurrent queue has been executed successfully and the output
is verified.

Potrebbero piacerti anche