题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
int List1Length = GetListLength(pHead1);
int List2Length = GetListLength(pHead2);
ListNode* pLongHead = pHead1;
ListNode* pShortHead = pHead2;
int diff = List1Length - List2Length;
if (List2Length > List1Length){
diff = List2Length - List1Length;
pLongHead = pHead2;
pShortHead = pHead1;
}
for(int i = 0; i < diff; i++){
pLongHead = pLongHead->next;
}
ListNode* r = nullptr;
while(pLongHead != nullptr && pShortHead != nullptr){
if(pLongHead == pShortHead){
r = pLongHead;
break;
}
pLongHead = pLongHead->next;
pShortHead = pShortHead->next;
}
return r;
}
int GetListLength(ListNode* pHead){
int r = 0;
while(pHead != nullptr){
pHead = pHead->next;
r++;
}
return r;
}
};
滴滴公司福利 1784人发布