题目描述
输入两个链表,找出它们的第一个公共结点。
AC C++ Solution:
思路: 因为第一个公共节点后面所有的节点都相同,首先计算两链表的长度差,抹平长度差距,然后再同时遍历,找到第一个公共节点
/*
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 dif = 0; //两链表长度差
int m = 0, n = 0;
ListNode* p1 = pHead1;
ListNode* p2 = pHead2;
while(p1) {
m++;
p1 = p1->next;
}
while(p2) {
n++;
p2 = p2->next;
}
if(m >= n) {
dif = m-n;
while(dif--)
pHead1 = pHead1->next;
}
else {
dif = n - m;
while(dif--)
pHead2 = pHead2->next;
}
while(pHead1 && pHead2) {
if(pHead1 == pHead2)
break;
pHead1 = pHead1->next;
pHead2 = pHead2->next;
}
return pHead1;
}
};