-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput_list.java
More file actions
44 lines (37 loc) · 1.51 KB
/
input_list.java
File metadata and controls
44 lines (37 loc) · 1.51 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
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class input_list {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input number of vertices
System.out.print("Enter the number of vertices: ");
int numberOfVertices = scanner.nextInt();
// Initialize the adjacency list
List<List<Integer>> adjacencyList = new ArrayList<>();
for (int i = 0; i < numberOfVertices; i++) {
adjacencyList.add(new ArrayList<>());
}
// Input number of edges
System.out.print("Enter the number of edges: ");
int numberOfEdges = scanner.nextInt();
// Input edges
System.out.println("Enter the edges (startVertex endVertex):");
for (int i = 0; i < numberOfEdges; i++) {
int startVertex = scanner.nextInt();
int endVertex = scanner.nextInt();
// Add edge to adjacency list
adjacencyList.get(startVertex).add(endVertex);
adjacencyList.get(endVertex).add(startVertex); // Uncomment for undirected graph
}
// Print the adjacency list
System.out.println("\nAdjacency List:");
for (int i = 0; i < numberOfVertices; i++) {
System.out.print(i + ": ");
for (int neighbor : adjacencyList.get(i)) {
System.out.print(neighbor + " ");
}
System.out.println();
}
}
}