题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
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 ) { struct ListNode *pt1=pHead1; struct ListNode *pt2=pHead2; // 取巧的方式,因为题目拼接只会把公共部分添加到末尾,所以两个链表末尾无论是有几个公共元素,末尾都是相同的 // 124 和 564 // 以下可以看成是把两个字符串拼接起来 // 124564 和 564124, 两个字符串从头开始遍历,末尾都是相同的 while(pt1!=pt2) { pt1 = pt1 ? pt1->next : pHead2; pt2 = pt2 ? pt2->next : pHead1; } return pt1; }