algorithm - Check if two linked lists merge. If so, where? -


This question can be old, but I could not think of an answer.

Say, there are two separate lists of lists, merge at a point ;

  1. We do not know the length
  2. We should parse each list only once.

Example of two mergent lists.

If

  • "Modification is not allowed" it means "You can change but end up They should be restored in ", and
  • We may have the following algorithm solution properly twice

. First, assume that the first list is length a + c and the second length is b + c , where c < / Code> Let them define the length of their normal "tail" (after mergepoint):

  x = a + cy = b + c  
< P> Since we do not know the length, we can do the x and y without additional iterations; You will see how.

Again, we repeat each list and vice versa while reversing them! If both iterators reach the merge point at the same time, then we find it by simply comparing it. Otherwise, an indicator will reach the merge point before the second.

After that, when the second itater reaches the merge point, it will not increase further on the normal tail. Instead of going back to the beginning of the list, which had reached the merge point first! Therefore, before reaching the end of the changed list (i.e. the beginning of the second list), he will give the total amount of a + b + 1 iterations. Let's call it z + 1 .

The first pointers pointing to the merge point will keep it constant, as long as the list does not reach the end. The number of iterations performed should be calculated and should be equal to x .

Again, this indicator returns and returns the lists again, but now it will not return to the beginning of the list originally started! Instead, this will go to the beginning of the second list! It should count the number of iterations done and equal to y .

So we know the following numbers:

  x = a + cy = b + cz = a + b  

Determine that

  a = (+ xy + z) / 2b = (- X + y + z) / 2 c = (+ x + yz) / 2  

that fixes the problem.


Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -