题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
#include <cstddef>
class Solution {
public:
//来一个求链表长度的函数 返回值:-1-传入的链表为nullptr >0-链表的长度
int LengthList(ListNode* pHead) const
{
if(pHead == nullptr) return -1;
size_t len = 0;
ListNode* p = pHead;
while(p != nullptr)
{
++len;
p = p->next;
}
return len;
}
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
size_t len1 = LengthList(pHead1);
std::size_t len2 = LengthList(pHead2);
//这里要判断是不是传入链表有空的情况
if(len1== -1 || len2 == -1) return nullptr;
ListNode* p = pHead1;
ListNode* q = pHead2;
if(len1>len2)
{
for(int i = 0;i != len1-len2;++i) p = p->next;
}
else
{
for(int i = 0;i != len2-len1;++i) q = q->next;
}
while(q != p)
{
q = q->next;
p = p->next;
}
return q;
}
};
查看10道真题和解析
三奇智元机器人科技有限公司公司福利 48人发布