简体   繁体   中英

Directed graph implementation in Java

I'm taking a class on data structures in java right now and we are to figure out how to implement a digraph class.
Just off the top, I thought that having a Linked List kind class with a value field and an array of link (self referential) fields like the code below:

    public class Digraph<T>
    {
        T vertex;
        Digraph<T>[] edge;

        public Digraph(T val, int maxDegree)
        {
            vertex = val;
            edge = new Digraph<T>[maxDegree];
        }
    }

After I wrote this out, I realized that this isn't a little to no mess method of approaching this prompt. How can I implement a digraph that isn't as messy as my code bit up there? Or is this an okay approach?

I think using your linked-list way to implement a graph is not a good ieda. Unlike linked list and tree, Graph is not a recursion structure in nature.

I will implement it based on the fact that a graph is consisted of a list of Vertexs, and each Vertex is connected to its neighbours by Edges :

class Graph<E> {
    public List<Vertex<E>> vertexs; 
}

class Vertex<E> {
    public E val;
    public List<Edge<E>> connections; 
}

class Edge<E> {
    public Vertex<E> source;
    public Vertex<E> destination;
}   

But the simplest way to represent a graph is to use an Adjacency_matrix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM