链式前向星

import java.util.Scanner;

public class AdjacencyTable {

    // 节点个数
    private int n;

    // 边的个数
    private int m;

    // 边的编号,从1开始
    private int edgeSerial = 0;

    // lastEdge[i] 保存以 i 为起点的最后一条边的编号
    private int[] lastEdge;

    // 全部的边
    private Edge[] edges;

    static class Edge {

        // 边的终点
        int end;

        // 边的权重
        int weight;

        // 与该边同起点的上一条边的编号
        int previous;

        public Edge(int end, int weight, int previous) {
            this.end = end;
            this.weight = weight;
            this.previous = previous;
        }
    }

    public AdjacencyTable(int n, int m) {
        this.n = n;
        this.m = m;
    }

    public void init() {
        lastEdge = new int[n + 1];
        edges = new Edge[m + 1];
    }

    public void add(int a, int b, int weight) {
       edges[++ edgeSerial] = new Edge(b, weight, lastEdge[a]);
       lastEdge[a] = edgeSerial;
    }

    public void visit(int x) {
        for (int i = lastEdge[x]; i != 0; i = edges[i].previous) {
            System.out.println(x + "--->" + edges[i].end + " weight = " + edges[i].weight);
        }
    }

    public void print() {

        for (int i = 1; i <= n; ++ i) {
            visit(i);
        }

    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while (in.hasNext()) {
            int n = in.nextInt();
            int m = in.nextInt();
            AdjacencyTable table = new AdjacencyTable(n , m);
            table.init();

            while (m -- > 0) {
                int a = in.nextInt();
                int b = in.nextInt();
                int weight = in.nextInt();
                table.add(a, b, weight);
            }

            table.print();

        }
    }
}