SHARE
TWEET

Graph

a guest Apr 24th, 2019 69 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //clang 3.8.0
  2. #include <stdlib.h>
  3. #include  <stdio.h>
  4. struct node{
  5. int vertex;
  6. struct node *next;
  7. };
  8. struct Graph{
  9. int numVertices;
  10. struct node **AdjLists;
  11. };
  12. typedef struct Graph Graph;
  13. typedef struct node Node;
  14. Node* createNode(int);
  15. Graph* createGraph(int);
  16. void addEdge(Graph*,int,int);
  17. void printGraph(Graph*);
  18.  
  19. int main(void)
  20. {
  21.  Graph *g=createGraph(4);
  22. addEdge(g,0,1);
  23. addEdge(g,0,2);
  24. addEdge(g,2,1);
  25. addEdge(g,3,4);
  26. printGraph(g);
  27.     return 0;
  28. }
  29. Node* createNode(int v){
  30. Node* newNode=malloc(sizeof(Node));
  31. newNode->vertex=v;
  32. newNode->next=NULL;
  33. return newNode;
  34. }
  35. Graph* createGraph(int Vertices){
  36. Graph *newGraph=malloc(sizeof(Graph));
  37. newGraph->numVertices=Vertices;
  38. newGraph->AdjLists=malloc(Vertices*sizeof(Node));
  39. for(int i=0;i<Vertices;i++ )
  40. newGraph->AdjLists[i]=NULL;
  41. return newGraph;
  42. }
  43. void addEdge(Graph *p,int src,int des){
  44. Node *newNode=createNode(des);
  45. newNode->next=p->AdjLists[src];
  46. p->AdjLists[src]=newNode;
  47. newNode=createNode(src);
  48. newNode->next=p->AdjLists[des];
  49. p->AdjLists[des]=newNode;
  50. }
  51. void printGraph(Graph *p){
  52. int i;
  53. for(i=0;i<p->numVertices;i++ ){
  54. Node *temp=p->AdjLists[i];
  55. printf("\n Adjacency list of vertex %d\n",i);
  56. while(temp){
  57. printf("%d->",temp->vertex);
  58. temp=temp->next;
  59. }
  60. printf("\n");
  61. }
  62. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top