题目描述:
输入两个链表,找出它们的第一个公共结点。
思路1:我们可以这样考虑,先把一个链表遍历一边,然后把所有的节点都存到HashMap的键中,然后遍历另一个链表,每次都和HashMap中的键来对比看看是否存在这个值,如果存在就是第一个公共的节点了。
思路2:注意到这个是单链表,那么第一个公共节点之后所连接的是同一个链! 就像丫字一样。那么我们可以统计所有的两条链表的长度,然后让长的链表先走比短的链表长的距离,然后一起齐头并进的走,就可以找到相同的节点了。
程序1:
程序2:
Copy:
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
HashMap<ListNode,Integer> map=new HashMap<>();
while(pHead1!=null){
map.put(pHead1,1);
pHead1=pHead1.next;
}
while(pHead2!=null){
if(map.containsKey(pHead2))
return pHead2;
pHead2=pHead2.next;
}
return null;
}
class
Solution {
public
:
ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {
int
len1 = findListLenth(pHead1);
int
len2 = findListLenth(pHead2);
if
(len1 > len2){
pHead1 = walkStep(pHead1,len1 - len2);
}
else
{
pHead2 = walkStep(pHead2,len2 - len1);
}
while
(pHead1 != NULL){
if
(pHead1 == pHead2)
return
pHead1;
pHead1 = pHead1->next;
pHead2 = pHead2->next;
}
return
NULL;
}
int
findListLenth(ListNode *pHead1){
if
(pHead1 == NULL)
return
0;
int
sum = 1;
while
(pHead1 = pHead1->next) sum++;
return
sum;
}
ListNode* walkStep(ListNode *pHead1,
int
step){
while
(step--){
pHead1 = pHead1->next;
}
return
pHead1;
}
};