思路一:两个链表长度,长的先走比短的多的那部分,再两个一起走,相遇就是那个节点
//求出两个链表的长度,然后让一个先走diff步,两个一起走相遇就是第一个公共节点
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1==NULL || pHead2==NULL)
return NULL;
int len1=getLen(pHead1);
int len2=getLen(pHead2);
while(len1>len2){
pHead1=pHead1->next;
len1--;
}
while(len2>len1){
pHead2=pHead2->next;
len2--;
}
while(pHead1!=pHead2){
pHead1=pHead1->next;
pHead2=pHead2->next;
}
return pHead1;
}
int getLen(ListNode* p){
int len=0;
while(p!=NULL){
p=p->next;
len++;
}
return len;
}
};
思路二:利用栈,保存链表,然后弹出,直到遇到第一个不相同的,那么上一个就是要求得点
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
stack<ListNode*> st1;
stack<ListNode*> st2;
if(pHead1==NULL || pHead2==NULL)
return NULL;
while(pHead1!=NULL){
st1.push(pHead1);
pHead1=pHead1->next;
}
while(pHead2!=NULL){
st2.push(pHead2);
pHead2=pHead2->next;
}
ListNode* ret=NULL;
while(!st1.empty() && !st2.empty() && st1.top()==st2.top()){
ret=st1.top();
st1.pop();
st2.pop();
}
return ret;
}
};