-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph adjacencylist
More file actions
87 lines (60 loc) · 1.59 KB
/
graph adjacencylist
File metadata and controls
87 lines (60 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
public class main {
public static void main(String[] args) {
Graph graph=new Graph();
graph.addNode('A');
graph.addNode('B');
graph.addNode('C');
graph.addNode('D');
graph.addNode('E');
graph.addEdge(0,1);
graph.addEdge(1,2);
graph.addEdge(1,4);
graph.addEdge(2,3);
graph.addEdge(2,4);
graph.addEdge(4,0);
graph.addEdge(4,2);
System.out.println(graph.checkEdge(1,4));
graph.print();
}
}
import java.util.ArrayList;
import java.util.LinkedList;
public class Graph {
ArrayList<LinkedList<Node>> alist;
Graph(){
alist=new ArrayList<>();
}
public void addNode(char data){
LinkedList<Node> currentList=new LinkedList<>();
currentList.add(new Node(data));
alist.add(currentList);
}
public void addEdge(int src,int dst){
Node dstNode=alist.get(dst).get(0);
alist.get(src).add(dstNode);
}
public boolean checkEdge(int src,int dst){
LinkedList<Node> currentList=alist.get(src);
Node dstNode=alist.get(dst).get(0);
for(Node node:currentList){
if(node==dstNode){
return true;
}
}
return false;
}
public void print(){
for(LinkedList<Node> currentList:alist) {
for (Node node : currentList) {
System.out.print(node.data+" -> ");
}
System.out.println();
}
}
}
public class Node {
char data;
Node(char data){
this.data=data;
}
}