题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://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) {
ListNode* p1 = pHead1;
ListNode* p2 = pHead2;
int i = 0, j = 0;
if (pHead1 == nullptr || pHead2 == nullptr) return nullptr;
while (p1 != nullptr || p2 != nullptr) {
if (p1 != nullptr) {
p1 = p1->next;
i++;
}
if (p2 != nullptr) {
p2 = p2->next;
j++;
}
}
if (i >= j) {
for (int k = 0; k < i - j; k++) {
pHead1 = pHead1->next;
}
} else {
for (int k = 0; k < j - i; k++) {
pHead2 = pHead2->next;
}
}
while (pHead1 != nullptr && pHead2 != nullptr) {
if (pHead1 == pHead2)return pHead1;
pHead1 = pHead1->next;
pHead2 = pHead2->next;
}
return nullptr;
}
};
比较两个链表的长度,然后让头指针在齐平位置同时出发即可。
查看23道真题和解析