/**
* 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) {
    int lenA=0,lenB=0;
    ListNode *tempA=headA;
    ListNode *tempB=headB;

//统计AB链的长度  

while(tempA){
      tempA=tempA->next;
      lenA++;
  }
while(tempB){
    tempB=tempB->next;
    lenB++;
}
if(lenA==0 || lenB==0) return NULL;

//保证长度A<B
if(lenA>lenB) return getIntersectionNode(headB,headA);

//对齐

   int len_dif=lenB-lenA;

    tempA=headA;
    tempB=headB;

    int i=0;
    while(i<len_dif){
      tempB=tempB->next;
      i++;
    }


while(tempA&&tempB&&tempA->val!=tempB->val){
  tempB=tempB->next;
  tempA=tempA->next;
}
return tempA;

}
};

相关文章:

  • 2021-09-29
  • 2021-07-16
  • 2021-05-22
  • 2022-01-01
  • 2021-12-25
  • 2021-06-16
猜你喜欢
  • 2022-12-23
  • 2021-10-27
  • 2022-12-23
  • 2021-09-06
  • 2021-10-03
相关资源
相似解决方案