/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ #include <cstdlib> class Solution { public: int getsize(ListNode* k) { //获取链表大小 int count = 0; while (k) { count++; k = k->next; } return count; } int abc (int a, int b) { //绝对值函数 if (a - b >= 0) { return a - b; }else{ return -(a - b); } } ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { if (!pHead1 || !pHead2){ return nullptr; } int count1 = getsize(pHead1); int count2 = getsize(pHead2); cout << abc(count1, count2) << endl; for (int i = 0; i < abc(count1, count2); i++) { //哪个链表长,就移动哪个链表,直到两个链表一样长 if (count1 >= count2) { pHead1 = pHead1->next; }else{ pHead2 = pHead2->next; } } while (pHead1 && pHead2) { //遍历两个链表,当出现相同的值,直接返回这个节点以及后边的节点 if (pHead1->val == pHead2->val) { return pHead1; } pHead1 = pHead1->next; pHead2 = pHead2->next; } return nullptr; } };