Last active
October 2, 2018 14:33
-
-
Save thmain/648947df7fff8d83fa9f0f3fabbbf8f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When i try to compile this, i get an error-
adjacent.java:18: error: not a statement list[source].addFirst[destination];