CodingInterview-两个链表的第一个公共结点

思路比较简单,先找出链表的长度,接着将长的链表先走一段长度,然后长链表和短链表一起继续走,直到遇到相同的节点。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
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==NULL || pHead2==NULL) return NULL;
int len1=GetListLength(pHead1);
int len2=GetListLength(pHead2);
ListNode* pLonger=pHead1;
ListNode* pShorter=pHead2;
if(len1<len2){
pLonger=pHead2;
pShorter=pHead1;
}
int lenDiff=len1>len2?len1-len2:len2-len1;
for(int i=0;i<lenDiff;i++){
pLonger=pLonger->next;
}
while(pLonger!=NULL && pShorter!=NULL){
if(pLonger==pShorter) return pLonger;
pLonger=pLonger->next;
pShorter=pShorter->next;
}
return NULL;
}
int GetListLength(ListNode* pHead){
ListNode* p=pHead;
int len=0;
while(p!=NULL){
len++;
p=p->next;
}
return len;
}
};