fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct node
  4. {
  5. int data;
  6. struct node *next;
  7. };
  8.  
  9.  
  10. int findIntersection(struct node* list1,struct node* list2)
  11. {
  12. struct node* head1=list1,*head2=list2;
  13. int count1=0,count2=0,diff;
  14. if(list1==NULL||list2==NULL)
  15. return -1;
  16. if(list1->next==NULL && list2->next==NULL)
  17. return -1;
  18.  
  19. while(head1)
  20. {
  21. count1++;
  22. head1=head1->next;
  23. }
  24. while(head2)
  25. {
  26. count2++;
  27. head2=head2->next;
  28. }
  29.  
  30. if(count1<count2)
  31. {
  32. diff=count2-count1;
  33. head1=list2;
  34. head2=list1;
  35. }
  36. else
  37. {
  38. diff=count1-count2;
  39. head1=list1;
  40. head2=list2;
  41. }
  42.  
  43. for (int i = 0; i < diff; ++i)
  44. head1=head1->next;
  45.  
  46. while(head1!=NULL && head2!=NULL)
  47. {
  48. if(head1==head2)
  49. return head1->data;
  50. head1=head1->next;
  51. head2=head2->next;
  52. }
  53.  
  54. return -1;
  55.  
  56.  
  57. }
  58.  
  59. int main()
  60. {
  61. struct node *new_node;
  62. struct node *head1=(struct node*)malloc(sizeof(struct node));
  63. head1->data=1;
  64.  
  65. struct node *head2=(struct node*)malloc(sizeof(struct node));
  66. head2->data=10;
  67.  
  68. new_node=(struct node*)malloc(sizeof(struct node));
  69. new_node->data=2;
  70. head1->next=new_node;
  71.  
  72. new_node=(struct node*)malloc(sizeof(struct node));
  73. new_node->data=3;
  74. head1->next->next=new_node;
  75.  
  76. new_node=(struct node*)malloc(sizeof(struct node));
  77. new_node->data=20;
  78. head2->next=new_node;
  79.  
  80. new_node=(struct node*)malloc(sizeof(struct node));
  81. new_node->data=4;
  82. head1->next->next->next=new_node;
  83. head2->next->next=new_node;
  84.  
  85. new_node=(struct node*)malloc(sizeof(struct node));
  86. new_node->data=5;
  87. head1->next->next->next->next=new_node;
  88.  
  89. head1->next->next->next->next->next=NULL;
  90.  
  91. int value=findIntersection(head1,head2);
  92.  
  93. printf("%d\n",value);
  94.  
  95. }
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
4