题目描述
输入两个链表,找出它们的第一个公共结点。
分析
这道题没有提环,所以假定链表没有环。
我们可以先简化一下问题,假设两个相交链表长度相等,那么我们遍历链表一、二,一次走一步然后查看是否相等,相等的那个节点就是相交点。
那么如果两个链表长度不相等,我们可以先让长度长的链表头向前走,看图。
假如是pHead1长的话,就让它先走黄色线段那么长,然后pHead1、pHead2一起走,直到相交。
代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
int len1=getListLength(pHead1);
int len2=getListLength(pHead2);
if(len1>len2){
for(int i=0;i<len1-len2;i++){
pHead1=pHead1->next;
}
}
else{
for(int i=0;i<len2-len1;i++){
pHead2=pHead2->next;
}
}
while(pHead1!=pHead2){
if(pHead1==NULL)return NULL;
pHead1=pHead1->next;
pHead2=pHead2->next;
}
return pHead1;
}
int getListLength(ListNode* head){ //求个长度
int length=0;
while(head!=NULL){
head=head->next;
length++;
}
return length;
}
};