BM10 | 两个链表的第一个公共结点
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=295&tqId=23257&sourceUrl=%2Fexam%2Foj
思路
统计两个链表的长度,让两个指针指向离公共点相同距离的结点
步骤
- 如果有一个链表为空,则返回空
- 设置变量统计两个链表的长度 len1 和 len2 ,让比较长的那个链表头指针先移动 |len1-len2| 个距离,然后两个链表指针同时向后移动一步,直到相遇,即为第一个公共结点。
正确答案
/*
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 == nullptr || pHead2 == nullptr) return nullptr;
int len1 = 0, len2 = 0;
ListNode* temp1 = pHead1;
ListNode* temp2 = pHead2;
while (temp1 != nullptr) {
len1++;
temp1 = temp1->next;
}
while (temp2 != nullptr) {
len2++;
temp2 = temp2->next;
}
temp1 = pHead1;
temp2 = pHead2;
if (len1 - len2 >= 0) {
for (int p = 0; p < len1 - len2; p++) {
temp1 = temp1->next;
}
} else {
for (int q = 0; q < len2 - len1; q++) {
temp2 = temp2->next;
}
}
while (temp1 != temp2) {
temp1=temp1->next;
temp2=temp2->next;
}
return temp1;
}
};
查看6道真题和解析
