之前王道的数据结构中做过,后面忘了,搞了一个双循环做的。
双循环代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* _head1 =headA;
ListNode* _head2 =headB;
while(_head1 != nullptr || _head2 != nullptr ){
while(_head1!=_head2 && _head2!=nullptr){
_head2 = _head2->next;
if(_head1 == _head2){
return _head1;
}
}
if(_head2 == nullptr){
_head1 = _head1->next;
if(_head1==nullptr){
return nullptr;
}
_head2 = headB;
}
if(_head1 == _head2){
return _head1;
}
}
return nullptr;
}
};
自觉时间复杂度太高,于是去查询有无时间复杂度为O(n)的方法,于是看到一个神中神的
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* a = headA;
ListNode* b = headB;
while (a != b)
{
a = a != nullptr ? a->next : headB;
b = b != nullptr ? b->next : headA;
}
return a;
}
};
出处:
作者:ffreturn
链接:https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/solutions/621146/cji-hu-shuang-bai-de-dan-ci-bian-li-jie-ups5w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
思路是:
思路
A长度为 a, B长度为b, 假设存在交叉点,此时 A到交叉点距离为 c, 而B到交叉点距离为d
后续交叉后长度是一样的,那么就是 a-c = b-d -> a+d = b+c
这里意味着只要分别让A和B额外多走一遍B和A,那么必然会走到交叉,注意这里边缘情况是,大家都走到null依然没交叉,那么正好返回null即可