/** * 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 *p1; struct ListNode *p2; p1 = pHead1; p2 = pHead2; while(p1 != p2) { p1 = (p1 == NULL)?pHead2:p1->next; p2 = (p2 == NULL)?pHead1:p2->next; } return p1; }
p1和p2把全部路径都走一遍,走到头了就换到对方的路径上,在没有公共节点的情况下,最终都会走到NULL。如果有公共节点,则最终会相交。
两个指针走的路径则都是链表1+链表2。