简体   繁体   English

两个链表的交点

[英]Intersection point of two linked lists

There are two singly linked lists in a system.一个系统中有两个单链表。 By some programming error, the end node of one of the linked list got linked to the second list, forming an inverted Y shaped list.由于一些编程错误,其中一个链表的结束节点链接到了第二个链表,形成了一个倒 Y 形链表。 Write a program to get the point where two linked list merge.编写一个程序来获取两个链表合并的点。

Here is my recursive function for that -这是我的递归 function -

int intersection(Node* head_ref1 , Node* head_ref2){
    Node* temp1 = head_ref1;
    Node* temp2 = head_ref2;
    if(temp1->next == temp2->next)
        return temp1->data;
        
    return intersection(temp1->next , temp2->next);
}

But it's not giving correct answer.但它没有给出正确的答案。 Please explain why I'm getting the error.请解释为什么我收到错误。

Node *outer_head = head_ref1;
while(outer_head -> next != null)
{

  Node *inner_head = head_ref2;
  while(inner_head -> next != null)
   {
    if(inner_head == outer_head)
    {
     //Here it is merging occured 
    }
    inner_head = inner_head -> next;
   }
  outer_head = outer_head -> next;
}

Complexity复杂

O(n1 * n2) O(n1 * n2)

Explanation解释

The outer loop is for each node of the first linked list and inner loop is for second linked list.外循环用于第一个链表的每个节点,内循环用于第二个链表。 In the inner loop, checking if any of nodes of the second list is same as the current node of the first linked list.在内部循环中,检查第二个链表的任何节点是否与第一个链表的当前节点相同。

The code below is O(max(l1,l2)) where l1 and l2 are the length of the lists.下面的代码是 O(max(l1,l2)) 其中 l1 和 l2 是列表的长度。 If you want to compare iterators rather than their values change *itr1;=*itr2 to itr1!=itr2;如果您想比较迭代器而不是它们的值,请将 *itr1;=*itr2 更改为 itr1!=itr2;

auto itr1 = L1.rbegin(),last1=itr1;
auto itr2 = L2.rbegin(),last2=itr2;

for (; ++itr1 != L1.rend() && ++itr2 != L2.rend(); last1++, last2++) {
        if (*itr1 != *itr2) break;
}

When it exists the loop the last common value is *last1=*last2当它存在循环时,最后一个公共值是 *last1=*last2

Edit: I see that you have a singly linked list.编辑:我看到你有一个单链表。 In that case iterate over both lists and add the elements or pointers to a stack each then keep popping the stacks until the tops are different在这种情况下,遍历两个列表并将元素或指针添加到每个堆栈,然后继续弹出堆栈直到顶部不同

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

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