I am reading a book on Algorithms which has following code. I am having difficulty in understanding some lines here.
I have shown my doubt lines in the following code as DOUBT LINE 1 and DOUBT LINE 2.
I have also commented a line as REFERENCE where I am having difficulty to comprehend.
Please elaborate about the DOUBT LINE 1 and DOUBT LINE 2.
#define MAXV 100 /* maximum number of vertices */
#define NULL 0 /* null pointer */
/* DFS edge types */
#define TREE 0 /* tree edge */
#define BACK 1 /* back edge */
#define CROSS 2 /* cross edge */
#define FORWARD 3 /* forward edge */
typedef struct edgenode {
int y; /* adjancency info */
int weight; /* edge weight, if any */
struct edgenode *next; /* next edge in list */
} edgenode;
typedef struct {
edgenode *edges[MAXV+1]; /* adjacency info */ //REFERENCE
int degree[MAXV+1]; /* outdegree of each vertex */
int nvertices; /* number of vertices in the graph */
int nedges; /* number of edges in the graph */
int directed; /* is the graph directed? */
} graph;
it is graph.h header and there it is also read and insert functions.
read_graph(graph *g, bool directed)
{
int i; /* counter */
int m; /* number of edges */
int x, y; /* vertices in edge (x,y) */
initialize_graph(g, directed);
scanf("%d %d",&(g->nvertices),&m);
for (i=1; i<=m; i++) {
scanf("%d %d",&x,&y);
insert_edge(g,x,y,directed);
}
}
insert_edge(graph *g, int x, int y, bool directed)
{
edgenode *p; /* temporary pointer */
p = malloc(sizeof(edgenode)); /* allocate storage for edgenode */
p->weight = NULL;
p->y = y;
p->next = g->edges[x]; //DOUBT LINE1
g->edges[x] = p; /* insert at head of list */ //DOUBT LINE 2
g->degree[x] ++;
if (directed == FALSE)
insert_edge(g,y,x,TRUE);
else
g->nedges ++;
}
Each vertex holds a set of edges. We can regard the set as unordered. At all times outside of the mutator functions, the pointer
g->edges[i]points to the firstedgenodeincident on theith vertex, orNULLotherwise. Then, thenextlinks in theedgenodepoint to other edges in the set, transitively.So, to add an edge, you first create a new edge, then assign it's
nextpointer the currently "first" node (DOUBT LINE 1), then assign theg->edges[i]pointer the newly created value (DOUBT LINE 2).Notice that the conditions I said need to exist above are both still satisfied, although the order of the nodes has changed - what was "previously" first is now second, and the new node is first. That's OK, because we're just storing a set - the order does not matter.
Before (=> traverses a 'next' link):
After: