Skip to main content

Merge point of linked lists

Question:
How do you find the merge point of two linked lists?

Merge point is the first common node of two linked lists. From this node onwards, the lists have same nodes.

Note: we are not talking about values in the nodes, but the actual addresses themselves.
In the diagram shown, 4 is the merge point of the two lists.

You may think that easy solution is traverse two list parallely and compare the respective nodes of the lists. But that does not work.

In the diagram shown, if you start with head of list1 and list2, if you compare addresses of 1 and 5, then addresses of 2 and 6, addresses of 3 and 4 and so on, you will never find a match.

An easy solution would be  to take one node at a time from first list and compare this with all nodes in second list. Then move on to second node of first list, compare it with all nodes of second list and so on. And continue this process until a match is found.

But this process has a complexity of O(n2).

Another method will be to find the lengths of two lists - say l1 and l2 and then find their difference (l1-l2). Then traverse l1-l2 nodes from the longer list. Now we have the points of equal lengths in two lists.

Next we can traverse paralelly and compare the nodes.
  • Find length of list - l1
  • Find length of list - l2
  • Find the difference - d = abs(l1-l2)
  • Traverse d nodes from longer list (from first list if l1 is larger, from second list if l2 is larger)
  • Repeat the loop as long as n1 and n2 are not null
    • Compare nodes n1 of list1 and n2 of list2.
    • If they are equal break the loop - this is merge point.
    • move to next nodes -- n1 = n1->next    and n2 = n2->next

 Here is our function. 

NODEPTR find_merge_point(NODEPTR l1,NODEPTR l2)
{
    int len1 = find_length(l1);
    int len2 = find_length(l2);
    if(len1>len2)
    {
       l1 = skip_nodes(l1,len1-len2);
    }else{
       l2 = skip_nodes(l2,len2-len1);
    }
    while(l1 && l2)
    {
        if(l1==l2)
            return l1;
         l1 = l1->next;
         l2 = l2->next;
    }
    return NULL;
}

We are finding the lengths of lists l1 and l2. If l1 is greater we are moving d (difference between lengths) nodes in l1. If not we are moving d noes in l2.

Next we compare l1 to l2. If they are unequal, both are set to next nodes. When l1 is equal to l2, we have found our point of merger of two lists.

If there is no such node, we return NULL.

And here you find two helper functions - skip_nodes() and find_length()

int find_length(NODEPTR head)
{
   int c =0;
   while(head)
   {
      c++;
      head = head->next;
   }
   return c;
}

NODEPTR skip_nodes(NODEPTR head, int num)
{
    while(num)
    {
       head = head->next;
       num--;
    }
    return head;
}

In fact, most lists we find do not have a merge point. :)

To test this function, we need to explicitly merge two lists using some tweak.

You can find the driver program for this here

Comments

Popular posts from this blog

Linked list in C++

A linked list is a versatile data structure. In this structure, values are linked to one another with the help of addresses. I have written in an earlier post about how to create a linked list in C.  C++ has a library - standard template library which has list, stack, queue etc. data structures. But if you were to implement these data structures yourself in C++, how will you implement? If you just use new, delete, cout and cin, and then claim it is your c++ program, you are not conforming to OOPS concept. Remember you have to "keep it together". Keep all the functions and variables together - in a class. You have to have class called linked list in which there are methods - append, delete, display, insert, find, find_last. And there will also be a data - head. Defining node We need a structure for all these nodes. A struct can be used for this purpose, just like C. struct node { int val; struct node * next; }; Next we need to define our class. W

Swap nodes of a linked list

Qn: Write a function to swap the adjacent nodes of a singly linked list.i.e. If the list has nodes as 1,2,3,4,5,6,7,8, after swapping, the list should be 2,1,4,3,6,5,8,7 Image from: https://tekmarathon.com Though the question looks simple enough, it is tricky because you don't just swap the pointers. You need to take care of links as well. So let us try to understand how to go about it. Take two adjacent nodes p1 and p2 Let prevnode be previous node of p1 Now link prevnode to p2 Link p2 to p1 Link p1 to next node of p2 So the code will be prevnode -> next = p2; p1 -> next = p2 -> next; p2 -> next = p1; But what about the start node or head? head node does not have previous node If we swap head with second node, modified head should be sent back to caller  To take care of swapping first and second nodes, we can write p1 = head; p2 = head -> next; p1 -> next = p2 -> next; p2 -> next = p1; head = p2;  Now we are read

Binary tree deletion - non-recursive

In the previous post we have seen how to delete a node of a binary search tree using recursion. Today we will see how to delete a node of BST using a non-recursive function. Let us revisit the 3 scenarios here Deleting a node with no children just link the parent to NULL Deleting a node with one child link the parent to  non-null child of node to be deleted Deleting a node with both children select the successor of node to be deleted copy successor's value into this node delete the successor In order to start, we need a function to search for a node in binary search tree. Did you know that searching in  a BST is very fast, and is of the order O(logn). To search Start with root Repeat until value is found or node is NULL If the search value is greater than node branch to right If the search value is lesser than node branch to left.  Here is the function NODEPTR find_node (NODEPTR root,NODEPTR * parent, int delval) { NODEPTR nd = root; NODEPTR pa = root; if (root -> v