Find Merge node in 2 link lists | PROGRAMMING INTERVIEWS
Question: There are 2 link lists merging at some node. Find the node, where these 2 lists merge.
- Find length (len1) of first link list.
- Find length (len2) of second link list.
- find diff = abs(len1 – len2)
- Traverse the bigger list from the first node till 'diff' nodes. Now we have two lists, which have equal no of nodes.
- Traverse both the lists in parallel till we come across a common node.
- struct node* findMergeNode(struct node* list1, struct node* list2)
- {
- int len1, len2, diff;
- struct node* head1 = list1;
- struct node* head2 = list2;
- len1 = getlength(head1);
- len2 = getlength(head2);
- diff = len1 - len2;
- if (len1 < len2)
- {
- head1 = list2;
- head2 = list1;
- diff = len2 - len1;
- }
- for(int i = 0; i < diff; i++)
- head1 = head1->next;
- while(head1 != NULL && head2 != NULL)
- {
- if(head1 == head2)
- return head1->data;
- head1= head1->next;
- head2= head2->next;
- }
- return NULL;
- }