|
| 1 | +// Leyla Abdullayeva - 1904010038 - Project2 |
| 2 | +#include <stdio.h> |
| 3 | +#include <stdlib.h> |
| 4 | + |
| 5 | +struct AdjListNode |
| 6 | +{ |
| 7 | + int dest; |
| 8 | + struct AdjListNode* next; |
| 9 | +}; |
| 10 | + |
| 11 | +struct AdjList |
| 12 | +{ |
| 13 | + struct AdjListNode *head; |
| 14 | +}; |
| 15 | + |
| 16 | +struct Graph |
| 17 | +{ |
| 18 | + int V; |
| 19 | + struct AdjList* array; |
| 20 | +}; |
| 21 | + |
| 22 | +struct AdjListNode* newAdjListNode(int dest) |
| 23 | +{ |
| 24 | + struct AdjListNode* newNode = |
| 25 | + (struct AdjListNode*) malloc(sizeof(struct AdjListNode)); |
| 26 | + newNode->dest = dest; |
| 27 | + newNode->next = NULL; |
| 28 | + return newNode; |
| 29 | +} |
| 30 | + |
| 31 | +struct Graph* createGraph(int V) |
| 32 | +{ |
| 33 | + struct Graph* graph = |
| 34 | + (struct Graph*) malloc(sizeof(struct Graph)); |
| 35 | + graph->V = V; |
| 36 | + |
| 37 | + graph->array = |
| 38 | + (struct AdjList*) malloc(V * sizeof(struct AdjList)); |
| 39 | + |
| 40 | + int i; |
| 41 | + for (i = 0; i < V; ++i) |
| 42 | + graph->array[i].head = NULL; |
| 43 | + |
| 44 | + return graph; |
| 45 | +} |
| 46 | + |
| 47 | +void addEdge(struct Graph* graph, int src, int dest) |
| 48 | +{ |
| 49 | + struct AdjListNode* newNode = newAdjListNode(dest); |
| 50 | + newNode->next = graph->array[src].head; |
| 51 | + graph->array[src].head = newNode; |
| 52 | + |
| 53 | + newNode = newAdjListNode(src); |
| 54 | + newNode->next = graph->array[dest].head; |
| 55 | + graph->array[dest].head = newNode; |
| 56 | +} |
| 57 | + |
| 58 | +void printGraph(struct Graph* graph) |
| 59 | +{ |
| 60 | + int v; |
| 61 | + for (v = 0; v < graph->V; ++v) |
| 62 | + { |
| 63 | + struct AdjListNode* pCrawl = graph->array[v].head; |
| 64 | + printf("\n Adjacency list of vertex %d\n head ", v); |
| 65 | + while (pCrawl) |
| 66 | + { |
| 67 | + printf("-> %d", pCrawl->dest); |
| 68 | + pCrawl = pCrawl->next; |
| 69 | + } |
| 70 | + printf("\n"); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +int main() |
| 75 | +{ |
| 76 | + int V = 5; |
| 77 | + struct Graph* graph = createGraph(V); |
| 78 | + addEdge(graph, 0, 1); |
| 79 | + addEdge(graph, 0, 4); |
| 80 | + addEdge(graph, 1, 2); |
| 81 | + addEdge(graph, 1, 3); |
| 82 | + addEdge(graph, 1, 4); |
| 83 | + addEdge(graph, 2, 3); |
| 84 | + addEdge(graph, 3, 4); |
| 85 | + |
| 86 | + printGraph(graph); |
| 87 | + |
| 88 | + return 0; |
| 89 | +} |
0 commit comments