思想:先计算出a和b的总长度,计算step=abs(a-b),然后将最长的链表先执行step次next,最后判断a->next和b->next
/**
* 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) {
//思想:先计算出a和b的总长度,计算step=abs(a-b),然后将最长的链表先执行step次next,最后判断a->next和b->next
ListNode *res=NULL;
if(headA==NULL ||headB==NULL) return NULL;
else
{
ListNode *one=headA;
ListNode *sec=headB;
int cnt1=0,cnt2=0;
while(one)
{
cnt1++;
one=one->next;
}
while(sec)
{
cnt2++;
sec=sec->next;
}
int step=abs(cnt1-cnt2);
if(cnt1>cnt2)
{
while(step--)
headA=headA->next;
}
else
{
while(step--)
headB=headB->next;
}
}
while(headA!=headB)
{
headA=headA->next;
headB=headB->next;
}
return headA;
}
};
官方题解:
/**
* 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 *A=headA;
ListNode *B=headB;
while(A!=B)
{
A=A==nullptr?headB:A->next;
B=B==nullptr?headA:B->next;
}
return B;
}
};