面试题37:两个链表的第一个公共结点
生活随笔
收集整理的這篇文章主要介紹了
面试题37:两个链表的第一个公共结点
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
輸入兩個鏈表,找出它們的第一個公共結點。鏈表結點定義如下:
題目分析
劍指Offer(紀念版)P193 思路三
代碼實現
ListNode* FindFirstCommonNode( 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)){pListHeadLong = pListHeadLong->m_pNext;pListHeadShort = pListHeadShort->m_pNext;}// 得到第一個公共結點ListNode* pFisrtCommonNode = pListHeadLong;return pFisrtCommonNode; }unsigned int GetListLength(ListNode* pHead) {unsigned int nLength = 0;ListNode* pNode = pHead;while(pNode != NULL){++ nLength;pNode = pNode->m_pNext;}return nLength; }
轉載于:https://www.cnblogs.com/xwz0528/p/4896147.html
總結
以上是生活随笔為你收集整理的面试题37:两个链表的第一个公共结点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 20135202闫佳歆-第二章家庭作业-
- 下一篇: 神经网络(1)--Non-linear