简体   繁体   English

如何找到 2 个单链表的公共节点?

[英]How do i find the common node point of 2 single linked lists?

My approach to this question was to use a hashmap for storing the addresses of first linked list and traversing the second array and checking whether i found the address or not.If it is found i would return the node at that address.我解决这个问题的方法是使用 hashmap 来存储第一个链表的地址并遍历第二个数组并检查我是否找到了地址。如果找到,我将返回该地址的节点。 This would take O(m+n),where m and n are lengths of linked list but here we are using O(Linear) space complexity.这需要 O(m+n),其中 m 和 n 是链表的长度,但这里我们使用 O(Linear) 空间复杂度。 I found another approach to this question which has constant space but same time complexity but it didn't clear my doubt.我找到了解决这个问题的另一种方法,它具有恒定的空间但相同的时间复杂度,但它并没有消除我的疑问。 link to the question 链接到问题

what if my input is如果我的输入是

    list 11 = 1 -> 2 -> 3 -> 4 -> 6 ->7;
    list l2 = 2 -> 9;

In this case my one time traversal of lists after truncating the extra length would become like this在这种情况下,我在截断额外长度后对列表的一次遍历将变成这样

   diff=4;   // i would advance the list 1 by 4 elements as it has greater length
   l1= 6-> 7;
   l2= 2 -> 9;

Here i lost my intersection node.在这里,我失去了我的交点节点。 Can someone help me with this?有人可以帮我弄这个吗?

That method is only valid when the input linked lists are the same from the intersection point like:该方法仅在输入链表与交点相同时有效,例如:

1 -> 2 -> 3 -> 4 -> 5

12 -> 11-> 10 -> 3 -> 4 -> 5

Here the two lists are the same from the intersection point 3.这里两个列表从交点 3 开始是相同的。

Only then that algorithm works.只有这样,该算法才有效。

Note:笔记:

This problem is basically given as to find the intersection point of an inverted Y-shaped list (combination of two lists)这个问题基本上是为了找到一个倒Y形列表(两个列表的组合)的交点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM