题目描述:
输入两个链表,找出它们的第一个公共结点。
思路:两种方法:
(1)借助外部空间stack或者vector
(2)不用外部空间,让较长的链表先走他们的长度差值步,然后一块走,找到相同的节点
代码:
class Solution {
public:
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == nullptr || pHead2 == nullptr)return nullptr;
vector<ListNode*>Vec1;
vector<ListNode*>Vec2;
ListNode*ptr_1 = pHead1;
ListNode*ptr_2 = pHead2;
while (ptr_1 != nullptr){
Vec1.push_back(ptr_1);
ptr_1 = ptr_1->next;
}
while (ptr_2 != nullptr){
Vec2.push_back(ptr_2);
ptr_2 = ptr_2->next;
}
if (*(Vec1.end()-1) != *(Vec2.end()-1))return nullptr;
int n = Vec1.size() - 1;
int m = Vec2.size() - 1;
while (n >= 0 && m >= 0){
if (Vec1[n] != Vec2[m])return Vec1[n+1];
n--;
m--;
}
if (n < 0)return pHead1;
else
return pHead2;
}
};
class Solution {
public:
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == nullptr || pHead2 == nullptr)return nullptr;
ListNode*ptr_1 = pHead1;
ListNode*ptr_2 = pHead2;
int n = 0;
int m = 0;
while (ptr_1 != nullptr){
n++;
ptr_1 = ptr_1->next;
}
while (ptr_2 != nullptr){
m++;
ptr_2 = ptr_2->next;
}
ptr_1 = pHead1;
ptr_2 = pHead2;
if (n >= m){
int temp = n - m;
while (temp > 0){
ptr_1 = ptr_1->next;
temp--;
}
}
else{
int temp = m - n;
while (temp > 0){
ptr_2 = ptr_2->next;
temp--;
}
}
while (ptr_1 != nullptr&&ptr_2 != nullptr){
if (ptr_1 == ptr_2)return ptr_1;
ptr_1 = ptr_1->next;
ptr_2 = ptr_2->next;
}
return nullptr;
}
};