题目地址:
https://www.acwing.com/problem/content/description/62/
输入两个链表,找出它们的第一个公共结点。当不存在公共节点时,返回空节点。
代码如下:
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode *findFirstCommonNode(ListNode *headA, ListNode *headB) {
int lenA = 0, lenB = 0;
for (auto t = headA; t; t = t->next) lenA++;
for (auto t = headB; t; t = t->next) lenB++;
while (lenA > lenB) {
headA = headA->next;
lenA--;
}
while (lenB > lenA) {
headB = headB->next;
lenB--;
}
while (headA != headB && headA) {
headA = headA->next;
headB = headB->next;
}
return headA;
}
};
时间复杂度 O ( l A + l B ) O(l_A+l_B) O(lA+lB),空间 O ( 1 ) O(1) O(1)。