CoderfromIN
03-02-2022, 05:55 AM
Hey, Can someone explain? There's a error in this code to find the node at which the intersection of two singly linked lists begins. Where is it going wrong? Ref - InterviewBit (https://www.interviewbit.com/c-interview-questions/)
// Function to get the intersection point
// of the given linked lists
int getIntersectionNode(Node* head1, Node* head2)
{
Node *curr1 = head1, *curr2 = head2;
// While both the pointers are not equal
while (curr1 != curr2) {
// If the first pointer is null then
// set it to point to the head of
// the second linked list
if (curr1 == NULL) {
curr1 = head2;
}
// Else point it to the next node
else {
curr1 = curr1->next;
}
// If the second pointer is null then
// set it to point to the head of
// the first linked list
if (curr2 == NULL) {
curr2 = head1;
}
// Else point it to the next node
else {
curr2 = curr2->next;
}
}
// Return the intersection node
return curr1->data;
}
// Function to get the intersection point
// of the given linked lists
int getIntersectionNode(Node* head1, Node* head2)
{
Node *curr1 = head1, *curr2 = head2;
// While both the pointers are not equal
while (curr1 != curr2) {
// If the first pointer is null then
// set it to point to the head of
// the second linked list
if (curr1 == NULL) {
curr1 = head2;
}
// Else point it to the next node
else {
curr1 = curr1->next;
}
// If the second pointer is null then
// set it to point to the head of
// the first linked list
if (curr2 == NULL) {
curr2 = head1;
}
// Else point it to the next node
else {
curr2 = curr2->next;
}
}
// Return the intersection node
return curr1->data;
}