Abstact
刷OJ时,遇到一个题:判断两个链表是否有merge?如果有?在哪?如下图:merge point在值为3的地方。
在StackOverflow上一个回答特别棒:check if two linked lists merge
现在记录下来。
Algorithm
算法很简单:同时遍历两个链表。设右边为current1(对应第一条链表),current2(对应第二条链表)。当current1到尽头后,使current1遍历第二条链表。同样当current2到尽头后:使其遍历第一条链表。
在第二次遍历时:current1==current2:此时是merge point。否则没有merge point。
Why
Implement
int findMergeNode(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
SinglyLinkedListNode* current1=head1,*current2 = head2;
while(current1 !=current2){
if(current1->next ==nullptr)
current1=head2;
else
current1=current1->next;
if (current2->next == nullptr)
current2 = head1;
else
current2 = current2->next;
}
return current1->data;
}