• 剑指offer——两个链表的第一个公共结点


    首先计算两个链表的长度m,n,让较长的链表先走|m-n|,然后两个链表一起走,直到找到元素相同的结点。

     1 #include <iostream>
     2 using namespace std;
     3 
     4 ListNode
     5 {
     6     int m_data;
     7     ListNode *m_next;
     8 };
     9 
    10 unsigned int GetListLength(ListNode* pHead)
    11 {
    12     unsigned int nLength=0;
    13     ListNode* pNode=pHead;
    14     while(pNode!=NULL)
    15     {
    16         ++nLength;
    17         pNode=pNode->m_next;
    18     }
    19 }
    20 
    21 ListNode* FindFirstCommonNode(ListNode* pHead1,ListNode* pHead2)
    22 {
    23     unsigned int nLength1=GetListLength(pHead1);
    24     unsigned int nLength2=GetListLength(pHead2);
    25     int nLengthDif=nLength1-nLength2;
    26     ListNode* pListLong=pHead1;
    27     ListNode* pListShort=pHead2;
    28     if (nLength2>nLength1)
    29     {
    30         pListLong=pHead2;
    31         pListShort=pHead1;
    32         nLengthDif=-nLengthDif;
    33     }
    34     for (int i=0;i<nLengthDif;i++)
    35     {
    36         pListLong=pListLong->m_next;
    37     }
    38     while((pListLong!=NULL)&&(pListShort!=NULL)&&(pListLong!=pListShort))
    39     {
    40         pListLong=pListLong->m_next;
    41         pListShort=pListShort->m_next;
    42     }
    43     ListNode* pFirstCommonNode=pListLong;
    44     return pFirstCommonNode;
    45 }



  • 相关阅读:
    浅析TCP /UDP/ IP协议
    大小端模式
    小技巧—计算内存
    浅谈启发式合并
    浅谈换根DP
    POJ 3585 Accumulation Degree
    OSGi类加载问题
    Redis缓存集群方案
    Tair分布式缓存
    Tedis:淘宝的Redis的Java客户端开发包
  • 原文地址:https://www.cnblogs.com/dgy5554/p/3973380.html
Copyright © 2020-2023  润新知