两个链表交集

/**
* 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;

}
};

posted @ 2015-07-20 09:51  *桔子*  阅读(347)  评论(0编辑  收藏  举报