https://leetcode.com/problems/intersection-of-two-linked-lists/
题意:判断两个链表是否有公共交点;
思路:先求每个链表的长度,然后把最长链表移动两个链表的长度差,然后两链表同步判断,即可求出是否有公共交点;
/**
* 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)
return nullptr;
if(!headB)
return nullptr;
ListNode *p,*q;
p = headA;
q = headB;
int cntA = 0,cntB = 0;
while(p){
cntA++;
p = p->next;
}
while(q){
cntB++;
q = q->next;
}
p = headA;//恢复p指向链表的开始处
q = headB;//恢复q指向链表的开始处
int i = abs(cntA-cntB);
if(cntA > cntB){
while(i--){
p = p->next;
}
}
else{
while(i--){
q = q->next;
}
}
while(p){
if(p == q){
return p;
}
p = p->next;
q = q->next;
}
return nullptr;
}
};