Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node {
  5. int vertex;
  6. struct node* next;
  7. };
  8.  
  9. struct node* createNode(int);
  10.  
  11. struct Graph {
  12. int numVertices;
  13. struct node** adjLists;
  14. };
  15.  
  16. struct Graph* createGraph(int vertices);
  17. void addEdge(struct Graph* graph, int src, int dest);
  18. void printGraph(struct Graph* graph);
  19.  
  20. int main() {
  21. struct Graph* graph = createGraph(6);
  22. addEdge(graph, 0, 1);
  23. addEdge(graph, 0, 2);
  24. printGraph(graph);
  25. return 0;
  26. }
  27.  
  28. struct node* createNode(int v) {
  29. struct node* newNode = malloc(sizeof(struct node));
  30. newNode->vertex = v;
  31. newNode->next = NULL;
  32. return newNode;
  33. }
  34.  
  35. struct Graph* createGraph(int vertices) {
  36. struct Graph* graph = malloc(sizeof(struct Graph));
  37. graph->numVertices = vertices;
  38. graph->adjLists = malloc(vertices * sizeof(struct node*));
  39.  
  40. int i;
  41. for (i=0; i<vertices; i++) graph->adjLists[i] = NULL;
  42. }
  43.  
  44. void addEdge(struct Graph* graph, int src, int dest) {
  45. struct node* newNode = createNode(dst);
  46. newNode->next = graph->adjLists[src];
  47. graph->adjLists[src] = newNode;
  48.  
  49. newNode = createNode(src);
  50. newNode->next = graph->adjLists[dest];
  51. graph->adjLists[dest] = newNode;
  52. }
  53.  
  54. void printGraph(struct Graph* graph) {
  55. int v;
  56. for (v=0; v<graph->numVertices; v++) {
  57. struct node* temp = graph->adjLists[v];
  58. printf("\nAdjacency list of vertex %d\n", v);
  59. while (temp) {
  60. printf("%d -> ", temp->vertex);
  61. temp = temp->next;
  62. }
  63. printf("\n");
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement