思路:
前提:
PA = headA,PB = headB (B链表头节点)
过程:
1.PA与PB同时向后遍历
2.若PA遍历完,PA = headB
PB遍历完,PB = headA
3.直到PA与PB指向相同节点(实际遍历过两次中的较短的链表即可)
证明过程:
图解:
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode * PA = headA;
ListNode * PB = headB;
while(PA != PB)
{
PA = PA? PA -> next : headB;
PB = PB? PB -> next : headA;
}
return PA;
}
};