面试题 02.07
1.问题描述
2.解决方案
简单来说,就是求两个链表交点节点的指针。交点不是数值相等,而是指针相等,思路呢也很清晰为了o(n)的时间复杂度,我们通过统计长度然后对齐指针,然后同时移动判断是否相等即可!
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
//统计长度
int lenA=0;
int lenB=0;
ListNode* t=headA;
while(t!= nullptr){
t=t->next;
lenA++;
}
t=headB;
while(t!= nullptr){
t=t->next;
lenB++;
}
//headA,headB到了同一长度起点
if(lenA>lenB){
for(int i=1;i<=lenA-lenB;i++){
headA=headA->next;
}
} else{
for(int i=1;i<=lenB-lenA;i++){
headB=headB->next;
}
}
//headA,headB一起移动
while(headB!= nullptr&&headA!= nullptr&&headA!=headB){
headA=headA->next;
headB=headB->next;
}
if(headA== nullptr&&headB== nullptr) return nullptr;
else return headA;
}
};