题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: int ListLength(ListNode* pHead) { int length = 0; if (pHead == nullptr) { return length; } ListNode* pNode = pHead; while (pNode != nullptr) { ++length; pNode = pNode->next; } return length; } ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { int length1 = ListLength(pHead1); int length2 = ListLength(pHead2); int sub = length1 - length2; ListNode* pListHeadLong = pHead1; ListNode* pListHeadShort = pHead2; if (length1 < length2) { pListHeadLong = pHead2; pListHeadShort = pHead1; sub = length2 - length1; } for (int i = 1; i <= sub; ++i) { pListHeadLong = pListHeadLong->next; } while (pListHeadLong != nullptr && pListHeadShort != nullptr && pListHeadLong != pListHeadShort) { pListHeadLong = pListHeadLong->next; pListHeadShort = pListHeadShort->next; } return pListHeadLong; } };