题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: int GetListLen(ListNode* pHead) { int len = 0; while (pHead) { len += 1; pHead = pHead->next; } return len; } ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) { int len1 = GetListLen(pHead1); int len2 = GetListLen(pHead2); int diff = abs(len1 - len2); // 获取两个链表长度差 // 确定长链表的头,先走diff步 ListNode* pLonger = pHead1; ListNode* pShorter = pHead2; if (len2 > len1) { pLonger = pHead2; pShorter = pHead1; } while (diff-- > 0) { pLonger = pLonger->next; } while (pLonger && pShorter && pLonger != pShorter) { pLonger = pLonger->next; pShorter = pShorter->next; } return pLonger; } };
2023 剑指-链表 文章被收录于专栏
2023 剑指-链表