题目描述 输入两个链表,找出它们的第一个公共结点。 https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13tqId=11189tPage=2rp=2ru=/ta/coding-interviewsqru=/ta/coding-interviews/question-rankin
题目描述
输入两个链表,找出它们的第一个公共结点。
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=13&tqId=11189&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题解:
class Solution {public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
ListNode *p1 = pHead1, *p2 = pHead2;
int l1 = 0, l2 = 0;
while (p1 != NULL) {
l1++;
p1 = p1->next;
}
while (p2 != NULL) {
l2++;
p2 = p2->next;
}
p1 = pHead1;
p2 = pHead2;
if (l1 > l2) {
for (int i = 0; i < l1 - l2; i++) {
p1 = p1->next;
}
while (p1 != NULL && p2 != NULL && p1 != p2) {
p1 = p1->next;
p2 = p2->next;
}
}
else {
for (int i = 0; i < l2 - l1; i++) {
p2 = p2->next;
}
while (p1 != NULL && p2 != NULL && p1 != p2) {
p1 = p1->next;
p2 = p2->next;
}
}
return p1;
}
};