- 应该假设每个节点 是用指针直针来连接, 不然必须要用递归或者遍历完才能说明是公共的。
公共的意思是在内存上占用的空间相同
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
ListNode *p1 = pHead1, *p2 = pHead2;
int len1 = lenofList(pHead1);
int len2 = lenofList(pHead2);
if(len1 == 0 || len2 == 0) return nullptr;
while(len1 > len2){
p1 = p1 -> next;
--len1;
}
while(len2 > len1){
p2 = p2 -> next;
--len2;
}
while(p1 != p2 && p1 != nullptr && p2 != nullptr){
p1 = p1 ->next ;
p2 = p2 ->next ;
}
return p1;
}
template <typename T>
inline int lenofList(T *pHead){
T *p = pHead;
int len = 0;
while(p != nullptr){
p = p -> next;
++len;
}
return len;
}
};