Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active October 2, 2018 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thmain/648947df7fff8d83fa9f0f3fabbbf8f8 to your computer and use it in GitHub Desktop.
Save thmain/648947df7fff8d83fa9f0f3fabbbf8f8 to your computer and use it in GitHub Desktop.
import java.util.LinkedList;
public class Graph {
int vertex;
LinkedList<Integer> list[];
public Graph(int vertex) {
this.vertex = vertex;
list = new LinkedList[vertex];
for (int i = 0; i <vertex ; i++) {
list[i] = new LinkedList<>();
}
}
public void addEdge(int source, int destination){
//add edge
list[source].addFirst(destination);
//add back edge ((for undirected)
list[destination].addFirst(source);
}
public void printGraph(){
for (int i = 0; i <vertex ; i++) {
if(list[i].size()>0) {
System.out.print("Vertex " + i + " is connected to: ");
for (int j = 0; j < list[i].size(); j++) {
System.out.print(list[i].get(j) + " ");
}
System.out.println();
}
}
}
public static void main(String[] args) {
Graph graph = new Graph(5);
graph.addEdge(0,1);
graph.addEdge(0, 4);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.printGraph();
}
}
@Mayank3299
Copy link

Mayank3299 commented Oct 2, 2018

When i try to compile this, i get an error-
adjacent.java:18: error: not a statement list[source].addFirst[destination];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment