Note:
两个指针都从头往后走,走到头了就从另一个头结点开始往后走,相遇的地方就是相交的地方
如果没有交点,两个指针会同时走到NULL
代码如下:
/**
* 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) {
auto p = headA, q = headB;
while(p != q){
if(!p) p = headB;
else p = p -> next;
if(!q) q = headA;
else q = q -> next;
}
return p;
}
};