题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ struct ListNode* FindFirstCommonNode(struct ListNode* pHead1, struct ListNode* pHead2 ) { // write code here struct ListNode* L1,*L2; L1=pHead1; L2=pHead2; int a=1,b=1; if(L1==NULL||L2==NULL)return NULL; while(L1->next){ a++; L1=L1->next; } while(L2->next){ b++; L2=L2->next; } L1=pHead1; L2=pHead2; if(a>b){ a=a-b; while(a--){ L1=L1->next; } }else{ a=b-a; while(a--){ L2=L2->next; } } while(L1!=L2){ L1=L1->next; L2=L2->next; } return L1; }