Problem Statement
You’re given the pointer to the head nodes of two linked lists that merge together at some node. Find the node at which this merger happens. The two head nodes will be different and neither will be NULL.
[List #1] a--->b--->c
\
x--->y--->z--->NULL
/
[List #2] p--->q
In the above figure, both list merges at node
x
.
Input Format
You have to complete the
You have to complete the
int FindMergeNode(Node* headA, Node* headB)
method which takes two arguments - the heads of the linked lists. You should NOT read any input from stdin/console.
Output Format
Find the node at which both lists merge and
Find the node at which both lists merge and
return
the data
of that node. Do NOT print anything to stdout/console.
Sample Input
1
\
2--->3--->NULL
/
1
1--->2
\
3--->Null
/
1
Sample Output
2
3
Explanation
1. As shown in the Input, 2 is the merge point.
2. Similarly 3 is merging point
1. As shown in the Input, 2 is the merge point.
2. Similarly 3 is merging point
/*
Find merge point of two linked lists
Node is defined as
struct Node
{
int data;
Node* next;
}
*/
int FindMergeNode(Node *headA, Node *headB)
{
// Complete this function
// Do not write the main method.
Node* tempA = headA;
Node* tempB = headB;
if(headA == NULL || headB == NULL){
return 0;
}
int countA = 0;
int countB = 0;
while(tempA != NULL){
countA += 1;
tempA = tempA->next;
}
while(tempB != NULL){
countB += 1;
tempB = tempB->next;
}
tempA = headA;
tempB = headB;
if(countA > countB){
int diff = countA - countB;
while(diff > 0){
tempA = tempA->next;
diff--;
}
while(tempA != tempB){
tempA = tempA->next;
tempB = tempB->next;
}
return tempA->data;
}else if(countA == countB){
while(tempA != tempB){
tempA = tempA->next;
tempB = tempB->next;
}
return tempA->data;
}else{
int diff = countB - countA;
while(diff > 0){
tempB = tempB->next;
diff--;
}
while(tempA != tempB){
tempA = tempA->next;
tempB = tempB->next;
}
return tempB->data;
}
}
No comments:
Post a Comment