两个指针分别把两个链表a,b各走一遍,因为len(a + b) = len(b + a),所以相遇的时候就是第一个公共节点了。
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
ListNode *ta = pHead1, *tb = pHead2;
while (ta != tb) {
ta = ta ? ta->next : pHead2;
tb = tb ? tb->next : pHead1;
}
return ta;
}
};


京公网安备 11010502036488号