Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <assert.h>
- struct TList {
- int target;
- int peso;
- struct TList* next;
- };
- typedef struct TList* List;
- struct TGraph {
- List *adj;
- int nodes_count;
- };
- typedef struct TGraph* Graph;
- List appendNodeList(List L, int target);
- List initNodeList(int info);
- Graph initGraph(int nodes_count);
- void addEdge(Graph G, int source, int target);
- void printList(List L);
- void printGraph(Graph G);
- void printGraphAux(Graph G);
- Graph initGraph(int nodes_count) {
- Graph G = (Graph)malloc(sizeof(struct TGraph));
- G->adj = (List *)calloc(nodes_count, sizeof(List));
- G->nodes_count = nodes_count;
- return G;
- }
- void addEdge(Graph G, int source, int target) {
- assert(G != NULL);
- assert(source < G->nodes_count);
- assert(target < G->nodes_count);
- if (source != target) {
- G->adj[source] = appendNodeList(G->adj[source], target);
- }
- }
- List appendNodeList(List L, int target) {
- if (L != NULL) {
- if (L->target != target) {
- L->next = appendNodeList(L->next, target);
- }
- } else {
- L = initNodeList(target);
- }
- return L;
- }
- List initNodeList(int info) {
- List L = (List)malloc(sizeof(struct TList));
- L->target = info;
- L->next = NULL;
- return L;
- }
- void printGraphAux(Graph G) {
- if (G != NULL) {
- int x = 0;
- for (x = 0; x < G->nodes_count; x++) {
- printf("%d -> ", x);
- printList(G->adj[x]);
- printf("\n");
- }
- }
- }
- void printGraph(Graph G) {
- printGraphAux(G);
- printf("\n\n");
- }
- void printList(List L) {
- if (L != NULL) {
- printf(" %d(%d) ", L->target, L->peso);
- printList(L->next);
- }
- }
- int main()
- {
- int n,e,i,v,u,l;
- struct TGraph *G;
- printf("\nEnter the number of vertices - ");
- scanf("%d",&n);
- G = initGraph(n);
- printf("\nEnter the number of edges - ");
- scanf("%d",&e);
- printf("\nVertices are - ");
- for(i=0;i<n;i++)
- printf("%d ",i);
- printf("\nEnter the edges separated by space - ");
- for(i=0;i<e;i++)
- {
- scanf("%d%d",&v,&u);
- addEdge(G,v,u);
- }
- printGraph(n);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement