
三种解法实现,第三种有点巧妙,值得考虑:
暴力遍历:
/**
* 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) {
if(headA==nullptr||headB==nullptr)
return nullptr;
ListNode *curA=headA,*curB=headB;
while(curA!=nullptr){
while(curB!=nullptr){
if(curB==curA)
return curA;
curB = curB->next;
}
curA=curA->next;
curB = headB;
}
return nullptr;
}
};
Hash表:
/**
* 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) {
if(headA==nullptr||headB==nullptr)
return nullptr;
ListNode *curA=headA,*curB=headB;
unordered_set<ListNode*> data;
while(curA!=nullptr){
data.insert(curA);
curA=curA->next;
}
while(curB!=nullptr){
if(data.find(curB)!=data.end())
return curB;
curB = curB->next;
}
return nullptr;
}
};
双指针:
/**
* 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) {
if(headA==nullptr||headB==nullptr)
return nullptr;
ListNode *curA=headA,*curB=headB;
bool signA=true,signB=true;
while(curA!=nullptr||curB!=nullptr){
if(curA==curB&&curA!=nullptr)
return curA;
curA = curA->next;
curB = curB->next;
if(curA==nullptr&&signA){
curA=headB;
signA=false;
}
if(curB==nullptr&&signB){
curB=headA;
signB=false;
}
}
return nullptr;
}
};
本文介绍了解决链表交点问题的三种方法:暴力遍历、使用Hash表和双指针技巧。通过对比不同算法的时间和空间复杂度,探讨了各自的优缺点和适用场景。
1880

被折叠的 条评论
为什么被折叠?



