I am trying to represent a graph using the adjacency list representation of graphs. My code compiles correctly but shows incorrect result, I can't seem to find the logical inconsistency in my code. This is a sample input and output
Enter the number of Vertices
4
Enter the number of Edges
6
Enter the Edges
0 1
1 2
2 3
3 0
0 2
1 3
Adjacency list of vertex 0 head -> 0-> 2
Adjacency list of vertex 1 head -> 1-> 3
Adjacency list of vertex 2 head -> 2
Adjacency list of vertex 3 head -> 3
Note here that 0 is also connected to 1
2 is also connected to 1 and 0
struct grnode {
long long num;
struct grnode *next;
};
struct graph {
long long v;
long long e;
struct grnode *adj;
};
struct graph *adjlistgr(){
long long i,x,y;
struct grnode *temp;
struct graph *g = (struct graph*)malloc(sizeof(struct graph));
if (!g) {
printf("memory error");
return;
}
// here we scanf the num of vertices and edges
printf("Enter the number of Vertices \n");
scanf("%lld", &g->v);
printf("Enter the number of Edges\n");
scanf("%lld", &g->e);
g->adj = malloc(g->v*sizeof(struct grnode));
for (i = 0; i < g->v; i++)
{
g->adj[i].num = i;
g->adj[i].next = &g->adj[i];
}
printf("Enter the Edges\n");
for (i = 0; i < g->e;i++)
{ // now we scan the edges
scanf("%lld %lld", &x,&y);
temp = (struct grnode*)malloc( sizeof( struct grnode*));
temp->num = y;
temp->next = &g->adj[x];
g->adj[x].next = temp;
temp = (struct grnode*)malloc( sizeof( struct grnode*));
temp->num = y;
temp->next = &g->adj[y];
g->adj[y].next = temp;
}return g;
}
void printgraph(struct graph* graph)
{
int n;
for (n = 0; n < graph->v; ++n)
{
// struct grnode *pCrawl = graph->adj[n].num;
struct grnode *temp;
temp = (struct grnode*)malloc( sizeof( struct grnode*));
temp->next=&graph->adj[n];
temp=temp->next;
printf("\n Adjacency list of vertex %d\n head ", n);
long long s=temp->num;
do
{
printf("-> %d", temp->num);
temp = temp->next;
}while(temp->num!=s);
printf("\n");
}}
int main(){
struct graph *mylist=adjlistgr();
printgraph(mylist);
}