Finding the intersecting node from two intersecting linked lists

前端 未结 6 1519
旧巷少年郎
旧巷少年郎 2020-11-30 22:19

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 kno

6条回答
  •  借酒劲吻你
    2020-11-30 23:07

    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.

提交回复
热议问题