很妙很妙!但是一开始想不出来
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == nullptr || pHead2 == nullptr) {
return nullptr;
}
ListNode *ptr1 = pHead1, *ptr2 = pHead2;
while (ptr1 != ptr2) {
// 两链表总长度之和是相等的!
ptr1 = ptr1 ? ptr1->next : pHead2;
ptr2 = ptr2 ? ptr2->next : pHead1;
}
return ptr1;
}
};