我是靠谱客的博主 活力小蝴蝶,这篇文章主要介绍两个链表交集,现在分享给大家,希望可以做个参考。

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

}
};

转载于:https://www.cnblogs.com/julie-yang/p/4660591.html

最后

以上就是活力小蝴蝶最近收集整理的关于两个链表交集的全部内容,更多相关两个链表交集内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(98)

评论列表共有 0 条评论

立即
投稿
返回
顶部