zoukankan      html  css  js  c++  java
  • 两个链表的第一个公共节点

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

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

    /*
    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;
    
        }
    
        
    };
  • 相关阅读:
    ajax小白理解
    Once more
    win滚动条样式修改
    NOIP2018游记
    Stirling数笔记
    【Start From Here】HNOI2018 滚粗记
    6面相对象
    5方法定义及调用
    Java4数组
    Java3流程控制语句
  • 原文地址:https://www.cnblogs.com/cgy1012/p/11426971.html
Copyright © 2011-2022 走看看