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

因为两个链表长度不一致  又长又短  而后面部分是公共的,所以求出长链表长度和短链表长度

让长链表把他俩之间的差距先走完,然后两个链表并行的走,直到碰到第一个相同的节点

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
    if(pHead1==nullptr||pHead2==nullptr)
        return nullptr;
        
        ListNode * pHeadnew1=pHead1;
        ListNode * pHeadnew2=pHead2;
      unsigned int length1=getlistlength(pHeadnew1);
      unsigned int length2=getlistlength(pHeadnew2);
      unsigned int distance;
        if(length1>length2)
        {
        distance =length1-length2; 
            
         while(distance)  
         {
          pHeadnew1=pHeadnew1->next;
          --distance;
         }
            
            
           
        }  else
        {
          distance =length2-length1; 
         
         while(distance)  
         {
          pHeadnew2=pHeadnew2->next;
          --distance;
         }
            
        }
       
        //链表在此处已经对齐了
        
        while(pHeadnew1!=pHeadnew2&&(pHeadnew1!=nullptr)&&(pHeadnew2!=nullptr))//是相同节点
        {
            
         pHeadnew1=pHeadnew1->next;   
         pHeadnew2=pHeadnew2->next;      
            
        }
        
        ListNode *  pfirstcommon = pHeadnew1;
            
        return pfirstcommon;
        
    }
public:
   unsigned int getlistlength(ListNode* phead)
    {
        if (phead==nullptr)
          return 0;
      unsigned int length=0;
        while(phead)
        {
         phead = phead->next;
            length++;
        }
        return length;

    }

    
};

 

posted @ 2019-08-28 22:29  高颖1995  阅读(114)  评论(0编辑  收藏  举报