剑指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 }