题解 | 两个链表的第一个公共结点
两个链表的第一个公共结点
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) {
auto list_count = [](ListNode* node) -> int {
int i = 0;
while (node != nullptr) {
++i;
node = node->next;
}
return i;
};
int list1_node_count = list_count(pHead1);
int list2_node_count = list_count(pHead2);
if (list1_node_count == 0 || list2_node_count == 0) {
return nullptr;
}
ListNode* p = pHead1;
ListNode* q = pHead2;
if (list1_node_count > list2_node_count) {
for (int i = 0; i < list1_node_count - list2_node_count; ++i) {
p = p->next;
}
} else {
for (int i = 0; i < list2_node_count - list1_node_count; ++i) {
q = q->next;
}
}
while (p != q) {
p = p->next;
q = q->next;
}
if (p == nullptr) {
return nullptr;
} else {
return p;
}
}
};
查看26道真题和解析