用Java集合实现有向图的领接表存储

1.ArrayList+LinkedList

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    static final int MAX=10;
    public static void main(String[] args) {
        Scanner cin=new Scanner(System.in);
        ArrayList<LinkedList<Edge>> arrayList=new ArrayList<LinkedList<Edge>>(MAX);
        for(int i=0;i<MAX;i++){
            LinkedList<Edge> temp=new LinkedList<>();
            arrayList.add(temp);
        }
        int T=cin.nextInt();
        int from,to,weigth;
        for(int i=0;i<T;i++){
            from=cin.nextInt();
            to=cin.nextInt();
            //weigth=cin.nextInt();
            weigth=0;
            arrayList.get(from).add(new Edge(to,weigth));
        }
        for(int i=1;i<MAX;i++){
            ArrayList<Edge> temp=arrayList.get(i);
            if (temp.size()==0)
                continue;
            System.out.print(i+":");
            for(Edge edge:temp){
                System.out.print(i+"-"+edge.next+" ");
            }
            System.out.println();
        }
    }
}
class Edge{
    public int next;
    public int weigth;
    Edge(){
    }
    Edge(int next,int weigth){
        this.next=next;
        this.weigth=weigth;
    }
}

2.ArrayList嵌套

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    static final int MAX=10;
    public static void main(String[] args) {
        Scanner cin=new Scanner(System.in);
        ArrayList<ArrayList<Edge>> arrayList=new ArrayList<ArrayList<Edge>>(MAX);
        for(int i=0;i<MAX;i++){
            ArrayList<Edge> temp=new ArrayList<>();
            arrayList.add(temp);
        }
        int T=cin.nextInt();
        int from,to,weigth;
        for(int i=0;i<T;i++){
            from=cin.nextInt();
            to=cin.nextInt();
            //weigth=cin.nextInt();
            weigth=0;
            arrayList.get(from).add(new Edge(to,weigth));
        }
        for(int i=1;i<MAX;i++){
            ArrayList<Edge> temp=arrayList.get(i);
            if (temp.size()==0)
                continue;
            System.out.print(i+":");
            for(Edge edge:temp){
                System.out.print(i+"-"+edge.next+" ");
            }
            System.out.println();
        }
    }
}
class Edge{
    public int next;
    public int weigth;
    Edge(){
    }
    Edge(int next,int weigth){
        this.next=next;
        this.weigth=weigth;
    }
}

效果图:
在这里插入图片描述
一种比领接表更节约空间的算法:链式前向星
该算法是用三个数组模拟链表的操作,分别表示链表的头结点、数据域、指针域,可自行百度了解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值