题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
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) {
if(pHead1 == nullptr || pHead2 == nullptr) return nullptr;
ListNode* p = pHead1, *q = pHead2;
while(p != q){
p = p==nullptr ? pHead1 : p->next;
q = q==nullptr ? pHead2 : q->next;
}
if(p==nullptr) return nullptr;
return p;
}
};
循环遍历,直到两个指针相等,如果都为nullptr则没有合并结点,否则就定位到合并结点