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

后端 未结 26 1443
陌清茗
陌清茗 2020-12-07 06:43

This question may be old, but I couldn\'t think of an answer.

Say, there are two lists of different lengths, merging at a point; how do we know wher

26条回答
  •  一个人的身影
    2020-12-07 07:35

    We can use two pointers and move in a fashion such that if one of the pointers is null we point it to the head of the other list and same for the other, this way if the list lengths are different they will meet in the second pass. If length of list1 is n and list2 is m, their difference is d=abs(n-m). They will cover this distance and meet at the merge point.
    Code:

    int findMergeNode(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
        SinglyLinkedListNode* start1=head1;
        SinglyLinkedListNode* start2=head2;
        while (start1!=start2){
            start1=start1->next;
            start2=start2->next;
            if (!start1)
            start1=head2;
            if (!start2)
            start2=head1;
        }
        return start1->data;
    }
    

提交回复
热议问题