There are two singly linked lists where end nodes of one linked list got linked into the second list, forming aY (or T ) shaped list. Write a program to get the point where two linked lists got merged
belongs to collection: Interview C++ coding problems/challenges | Linked list
All Answers
total answers (1)

C++ programming
Pre-requisite:
Algorithm:
1. Declare set 's' to store nodes of the linked list; 2. Declare and define two pointer to node type variable Node* temp1=head1,*temp2=head2 //for traversing 3. While(temp1){ //until the first linked list is traversed Insert all the nodes (pointer to nodes of course) to the set; //remember nodes to be entered not the data value Insert(s, temp1); temp1=temp1->next; END While 4. While(temp2) IF (if temp2 is not present in the set) //not part of merged tail temp2=temp2->next; Else return temp2->data; //first intersection point found End IF-ELSE End WhileNote:
The nodes (pointer to nodes) are to be inserted into the set, not the node data. Let's say for an input example both heads have the same input data (for example say 1), but nodes are actually different (no intersection there). But if we maintain the set with node data, then that will return the 1, which is the wrong answer.
1 → 2 → 3 → 6 ← 4 ← 1 ↓ 8 ↓ NULLFor the above example, answer will be 1 if we start inserting node->data to the set instead of node. But the actual answer is 6.
Explanation with example:
The above algorithm is pretty simple and self-explanatory. Discussion for above example: After processing the first list the set contains: Pointer to Node having value 1 Pointer Node having value 2 Pointer to Node having value 3 Pointer Node having value 6 Pointer Node having value 8 NULL When second list is processed and checked, Pointer to node having value 1 is not in set (any doubt!Why? think yourself) Pointer to node having value 4 is not in set (No doubt) Pointer to node having value 6 is in the set (then what’s the difference between the first case where you have doubt!!! Reason is different address of the nodes though same value since those are different node, but in the second case the common node is same node) Thus it returns 6.C++ implementation:
Output