Vinicius Coelho
Vinicius Coelho

Reputation: 130

A graph can be implemented as a list?

A teacher asked me to implement the Circle Line of the London Underground on the graphs class. As i see, the yellow line can be represented as a graph and also as a circular linked list.

Circle line

On my last graph algorithm i have created this struct:

struct graph { int info; struct graph *edge[3]; };

It's correct to implement the Circle Line graph like below? Or i would be making it a linked list instead of a graph?

struct graph{ int info; struct graph *next; struct graph *prev; }

Upvotes: 1

Views: 354

Answers (1)

rowan.G
rowan.G

Reputation: 747

I would make a circular doubly linked list like the 2nd suggestion you have. it easier I think as the first suggestion. but only if every object has 2 vertices.

linked list is a type of list btw.

If you have a variable amount of vertices you can just have a variable amount of pointers like this:

struct graph {
    int info;
    struct graph **edge;
};

and then allocate it to whatever amount you need, so for instance if you want to have a node with 6 edges you can just do:

struct graph my_graph;

my_graph.edge = malloc(6 * sizeof(my_graph *));
if (my_graph.edge == NULL) {
    // allocation error
} 

from here you can connect the 6 edges to other objects.

Upvotes: 1

Related Questions