两个链表的第一个公共结点(面试题 37)

来源:互联网 发布:阿里云优惠口令 编辑:程序博客网 时间:2024/05/08 14:10

题目:输入两个链表,找出它们的第一个公共结点。

#include "iostream"using namespace std;struct ListNode{int m_nKey;ListNode* m_pNext;};unsigned int GetListLength(ListNode* pHead){unsigned int nLength =0;ListNode* pNode =pHead;while(pNode!=NULL){++nLength;pNode =pNode->m_pNext;}return nLength;}ListNode* FindFirstCommenNode(ListNode* pHead1,ListNode* pHead2){//得到两个链表的长度unsigned int nLength1 =GetListLength(pHead1);unsigned int nLength2 =GetListLength(pHead2);int nLengthDif =nLength1-nLength2;ListNode* pListHeadLong =pHead1;ListNode* pListHeadshort =pHead2;if (nLength2>nLength1){pListHeadLong =pHead2;pListHeadshort =pHead1;nLengthDif =nLength2 -nLength1;}//先在长链表上走几步,再同时在两个链表上遍历for (int i=0;i<nLengthDif;i++){pListHeadLong =pListHeadLong->m_pNext;}while((pListHeadLong!=NULL)&&(pListHeadshort !=NULL)&&(pListHeadLong !=pListHeadshort)){pListHeadshort =pListHeadshort->m_pNext;pListHeadLong =pListHeadLong->m_pNext;}ListNode* pFirstCommenNode =pListHeadLong;return pFirstCommenNode;}


0 0
原创粉丝点击