HCL Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
public bool findIntersectionof2LinkList()
{
curr = Head;
curr1 = Head1;
//traverse list 1
while (curr != null)
{
curr.isVisited = true;
curr = curr.next;
}
//traverse list2 and find the intersection
while (curr1 != null)
{
if (curr1.isVisited)
return true;
else
curr1 = curr1.next;
}
return false;
}
public bool findIntersectionof2LinkList(Node Head, Node Head1)
{
Node curr = Head;
Node curr1 = Head1;
//traverse list 1
while (curr != null)
{
curr.isVisited = true;
curr = curr.next;
}
//traverse list2 and find the intersection
while (curr1 != null)
{
if (curr1.isVisited)
return true;
else
curr1 = curr1.next;
}
return false;
}
Step 1: if the linked lists are not empty, find the length of each linked list. Since they have a common end point, we will get length of common area of the linked lists too.
- BVarghese April 16, 2013Step 2: find the difference between the length of both list. Start traverse the biggest list till the difference in length between them, provided one of them is bigger than the other.
Step 3: now they are at the same remaining length. Traverse both of the together till both are pointing to the same next node.That node is the common node which is the merging point. If there is no such point, then they are not merged.