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;
    
        }
    
        
    };
  • 相关阅读:
    lucene中创建索引库
    商城后台上架商品列表查询的书写全过程
    Linux命令英文全称
    商品品牌分页、过滤、排序查询的完成流程
    axios使用步骤详解(附代码)
    使用CORS处理跨域请求
    npm 是干什么的?
    Mybatis通用Mapper介绍和使用
    FastDFS的理解和分析
    CDN服务的含义
  • 原文地址:https://www.cnblogs.com/cgy1012/p/11426971.html
Copyright © 2011-2022 走看看