题解 | 两个链表的第一个公共结点
两个链表的第一个公共结点
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* temp1 = pHead1; struct ListNode* temp2 = pHead2; while (temp1 != temp2) { if (temp1 == NULL) { temp1 = pHead2; } else { temp1 = temp1->next; } if (temp2 == NULL) { temp2 = pHead1; } else { temp2 = temp2->next; } } return temp1; }
两个链表同时遍历,如果两个链表相交,那么必然相遇,相遇后就是第一个公共节点。