剑指offer——两个链表的第一个公共结点
2014-09-09 15:02
337 查看
首先计算两个链表的长度m,n,让较长的链表先走|m-n|,然后两个链表一起走,直到找到元素相同的结点。
#include <iostream> using namespace std; ListNode { int m_data; ListNode *m_next; }; unsigned int GetListLength(ListNode* pHead) { unsigned int nLength=0; ListNode* pNode=pHead; while(pNode!=NULL) { ++nLength; pNode=pNode->m_next; } } ListNode* FindFirstCommonNode(ListNode* pHead1,ListNode* pHead2) { unsigned int nLength1=GetListLength(pHead1); unsigned int nLength2=GetListLength(pHead2); int nLengthDif=nLength1-nLength2; ListNode* pListLong=pHead1; ListNode* pListShort=pHead2; if (nLength2>nLength1) { pListLong=pHead2; pListShort=pHead1; nLengthDif=-nLengthDif; } for (int i=0;i<nLengthDif;i++) { pListLong=pListLong->m_next; } while((pListLong!=NULL)&&(pListShort!=NULL)&&(pListLong!=pListShort)) { pListLong=pListLong->m_next; pListShort=pListShort->m_next; } ListNode* pFirstCommonNode=pListLong; return pFirstCommonNode; }
相关文章推荐
- 剑指offer(四十四)之两个链表的第一个公共结点
- 《剑指offer》刷题笔记(时间空间效率的平衡):两个链表的第一个公共结点
- 《剑指Offer》学习笔记--面试题37:两个链表的第一个公共结点
- 《剑指offer》——两个链表的第一个公共结点
- (剑指offer)数组中的逆序对 两个链表的第一个公共结点
- 剑指Offer: 两个链表的第一个公共结点
- (剑指Offer)面试题37:两个链表的第一个公共结点
- (剑指offer)两个单向链表,找出它们的第一个公共结点
- 《剑指offer》两个链表的第一个公共结点
- 剑指offer(33)-两个链表的第一个公共结点
- 《剑指offer》-两个链表的第一个公共结点
- 剑指offer 37 两个链表的第一个公共结点
- [剑指offer学习心得]之:两个链表的第一个公共结点
- 《剑指offer》:[5]查找两个链表的第一个公共结点
- 剑指Offer 37 两个链表的第一个公共结点
- 两个链表的第一个公共结点(剑指offer)+链表
- 剑指Offer:面试题37 两个链表的第一个公共结点
- 剑指offer题解 两个链表的第一个公共结点
- 剑指offer系列源码-两个链表的第一个公共结点
- 牛客:剑指offer:两个链表的第一个公共结点(Java)