第一种思路:
用栈
第二种思路:
先遍历两个链表,得到各自长度,然后将长的那个链表先往后查找 两长度差的 步数。接着同时向后查找,直到找到相同的节点。
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {
int size1=0,size2=0;
ListNode* p1=pHead1;
ListNode* p2=pHead2;
while(pHead1!=NULL){
size1++;
pHead1=pHead1->next;
}
while(pHead2!=NULL){
size2++;
pHead2=pHead2->next;
}
pHead1=p1;
pHead2=p2;
if(size1>size2){
int n=size1-size2;
while(n--)
pHead1=pHead1->next;
}
else if(size1<size2){
int m=size2-size1;
while(m--)
pHead2=pHead2->next;
}
while(pHead1!=pHead2 &&pHead1!=NULL && pHead2!=NULL){
pHead1=pHead1->next;
pHead2=pHead2->next;
}
return pHead1;
}
};