解题思路
利用双指针,当一个指针走到尽头时 去走另一个指针走的路,循环一次就能走到相同的地方,因为走两次走的路一样长。
/**
* 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) {
if(headA==NULL||headB==NULL)return NULL;
ListNode *man=headA;
ListNode *woman=headB;
while(man!=woman)//相等条件有 同为NULL 或交点
{
man=man?man->next:headB;
woman=woman?woman->next:headA;
}
return man;
}
};