编辑代码

import java.util.*;

class Graph {
    private int V;
    private LinkedList<Integer> adjListArray[];

    // 构造函数
    Graph(int V) {
        this.V = V;
        adjListArray = new LinkedList[V];

        for (int i = 0; i < V; i++) {
            adjListArray[i] = new LinkedList<>();
        }
    }

    // 添加边
    void addEdge(int src, int dest) {
        adjListArray[src].add(dest);
        adjListArray[dest].add(src);
    }

    // 打印图
    void printGraph() {
        for (int v = 0; v < V; v++) {
            System.out.println("顶点 " + v + ":");
            for (Integer pCrawl : adjListArray[v]) {
                System.out.print(" -> " + pCrawl);
            }
            System.out.println("");
        }
    }

    public static void main(String args[]) {
        int V = 5;
        Graph graph = new Graph(V);

        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();
    }
}