码迷,mamicode.com
首页 > 其他好文 > 详细

两个链表交集

时间:2015-07-20 10:47:09      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

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

}
};

两个链表交集

标签:

原文地址:http://www.cnblogs.com/julie-yang/p/4660591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!