fork(8) download
  1. #include<iostream>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<vector>
  5.  
  6. using namespace std;
  7.  
  8. struct elem
  9. {
  10. int dest; // this the the node number(name) with which our source is connected.
  11. struct elem *next;
  12.  
  13. };
  14.  
  15. int addEdge(vector<elem *> &graph,int src,int dest)
  16. {
  17. struct elem *temp=(struct elem *)malloc(sizeof(struct elem));
  18. temp->dest=dest;
  19. temp->next=graph[src];
  20. graph[src]=temp;
  21. temp=(struct elem *)malloc(sizeof(struct elem));
  22. temp->dest=src;
  23. temp->next=graph[dest];
  24. graph[dest]=temp;
  25. return 0;
  26. }
  27.  
  28. void print(int v,vector<elem *> &graph)
  29. {
  30. int i;
  31. struct elem *temp;
  32. for(i=0;i<v;i++)
  33. {
  34. temp=graph[i];
  35. printf("node %d ",i);
  36. while(temp!=NULL)
  37. {
  38. printf(" -> %d",temp->dest);
  39. temp=temp->next;
  40. }
  41. printf("\n");
  42. }
  43. }
  44.  
  45. int main()
  46. {
  47. int v=5,i;
  48. vector<elem *> graph;
  49. for(i=0;i<v;i++)
  50. graph.push_back(NULL);
  51.  
  52. addEdge(graph, 0, 1);
  53. addEdge(graph, 0, 4);
  54. addEdge(graph, 1, 2);
  55. addEdge(graph, 1, 3);
  56. addEdge(graph, 1, 4);
  57. addEdge(graph, 2, 3);
  58. addEdge(graph, 3, 4);
  59. print(v,graph);
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
node 0  -> 4 -> 1
node 1  -> 4 -> 3 -> 2 -> 0
node 2  -> 3 -> 1
node 3  -> 4 -> 2 -> 1
node 4  -> 3 -> 1 -> 0