两个链表的第一个公共节点

题目描述

输入两个链表,找出它们的第一个公共结点。
 
 
 
 
提交链接:点击
 
 
 
 
思路:
 
   找两个链表的第一个公共节点。首先得考虑的是两个链表可能不等长,那么就需要首先得到两个链表的长度L1,L2。让长的那个链表先走(L2-L1)步,接下来就判断分别指向两个链表的指针是否相等就好了!
  
 
代码:
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        //Y字形的结构,首先得确定同时移动指针的位置
        int pLen1=0,pLen2=0;
        ListNode *t1=pHead1,*t2=pHead2;
        if(pHead1==NULL||pHead2==NULL) return NULL;
        for(;pHead1!=NULL;){
            pLen1++;
            pHead1=pHead1->next;
        }
        for(;pHead2!=NULL;){
            pLen2++;
            pHead2=pHead2->next;
        }
        if(pLen1>pLen2){
            int temp=pLen1-pLen2;
            for(int i=0;i<temp;i++){
                t1=t1->next;
            }
        }else{
            int temp=pLen2-pLen1;
            for(int i=0;i<temp;i++){
                t2=t2->next;
            }
        }
        while(t1!=NULL && t2!=NULL){
            if(t1==t2){
                return t1;
            }
            t1=t1->next;
            t2=t2->next;
        }
        return NULL;
    }
};
原文地址:https://www.cnblogs.com/logo-88/p/9839110.html