题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
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* plist) { int n = 0; while (plist != nullptr) { plist = plist->next; n++; } return n; } ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { int len1 = ListLength(pHead1); int len2 = ListLength(pHead2); int n = abs(len1 - len2); if (len1 >= len2) { for (int i = 0; i < n; i++) pHead1 = pHead1->next; } else { for (int i = 0; i < n; i++) pHead2 = pHead2->next; } while ((pHead1 != nullptr) && (pHead2 != nullptr) && (pHead1 != pHead2)) { pHead1 = pHead1->next; pHead2 = pHead2->next; } return pHead1; } };