Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the intersecting node from two intersecting linked lists

Suppose there are two singly linked lists both of which intersect at some point and become a single linked list.

The head or start pointers of both the lists are known, but the intersecting node is not known. Also, the number of nodes in each of the list before they intersect are unknown and both list may have it different i.e. List1 may have n nodes before it reaches intersection point and List2 might have m nodes before it reaches intersection point where m and n may be

  • m = n,
  • m < n or
  • m > n

One known or easy solution is to compare every node pointer in the first list with every other node pointer in the second list by which the matching node pointers will lead us to the intersecting node. But, the time complexity in this case will O(n2) which will be high.

What is the most efficient way of finding the intersecting node?

like image 896
Jay Avatar asked Feb 07 '10 10:02

Jay


People also ask

How do you find the intersection of two linked lists in C?

Get count of the nodes in the first list, let count be c1. Get count of the nodes in the second list, let count be c2. Get the difference of counts d = abs(c1 – c2) Now traverse the bigger list from the first node till d nodes so that from here onwards both the lists have equal no of nodes.

How do you traverse two linked lists?

Traversing is the most common operation in case of each data structure. For this purpose, copy the head pointer in any of the temporary pointer ptr. then, traverse through the list by using while loop.

How do you find the union of two linked lists?

Method 1 (Simple):Initialize the result list as NULL. Traverse list1 and look for every element in list2, if the element is present in list2, then add the element to the result. and then store it into our new list ans and return its head.


1 Answers

This takes O(M+N) time and O(1) space, where M and N are the total length of the linked lists. Maybe inefficient if the common part is very long (i.e. M,N >> m,n)

  1. Traverse the two linked list to find M and N.
  2. Get back to the heads, then traverse |M − N| nodes on the longer list.
  3. Now walk in lock step and compare the nodes until you found the common ones.

Edit: See more here.

like image 159
kennytm Avatar answered Oct 12 '22 02:10

kennytm