Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import java.util.

ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Graph {


private Map<Integer, List<Integer>> graph;

public Graph() {
this.graph = new HashMap<>();
}

public void addNode(int v) {


if (graph.containsKey(v)) {
System.out.println(v + " is already present in graph");
} else {
graph.put(v, new ArrayList<>());
}
}

public void addEdge(int v1, int v2) {


if (!graph.containsKey(v1)) {
System.out.println(v1 + " is not present in the graph");
} else if (!graph.containsKey(v2)) {
System.out.println(v2 + " is not present in the graph");
} else {
graph.get(v1).add(v2);
graph.get(v2).add(v1);
}
}

public void deleteEdge(int v1, int v2) {


if (!graph.containsKey(v1)) {
System.out.println(v1 + " is not present in the graph");
} else if (!graph.containsKey(v2)) {
System.out.println(v2 + " is not present in the graph");
} else {
List<Integer> list1 = graph.get(v1);
List<Integer> list2 = graph.get(v2);
if (list1.contains(v2)) {
list1.remove(Integer.valueOf(v2));
}
if (list2.contains(v1)) {
list2.remove(Integer.valueOf(v1));
}
}
}

public void deleteNode(int v) {


if (!graph.containsKey(v)) {
System.out.println(v + " is not present in graph");
} else {
graph.remove(v);
for (List<Integer> list : graph.values()) {
if (list.contains(v)) {
list.remove(Integer.valueOf(v));
}
}
}
}

public static void main(String[] args) {


Graph graph = new Graph();

graph.addNode(1);
graph.addNode(2);
graph.addNode(2);
graph.addNode(3);
graph.addEdge(1, 3);
graph.addEdge(2, 3);

System.out.println(graph.graph);
graph.deleteEdge(1, 3);
System.out.println(graph.graph);
graph.deleteNode(1);
System.out.println(graph.graph);

}
}

You might also like