文章作者:Tyan
博客:noahsnail.com | 优快云 | 简书
1. Description

2. Solution
- Version 1
/**
* 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) {
unordered_map<ListNode*, ListNode*> m;
ListNode* current = headA;
while(current) {
m[current] = current;
current = current->next;
}
current = headB;
while(current) {
if(m.find(current) != m.end()) {
return current;
}
current = current->next;
}
return nullptr;
}
};
- Version 2
/**
* 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 || !headB) {
return nullptr;
}
ListNode* pA = headA;
ListNode* pB = headB;
while(pA != pB) {
pA = pA->next;
pB = pB->next;
if(!pA && pB) {
pA = headB;
}
if(pA && !pB) {
pB = headA;
}
}
return pA?pA:nullptr;
}
};
本文深入探讨了链表交集问题的两种解决方案,一种利用哈希映射,另一种采用双指针技巧,通过示例代码详细解释了如何在两个链表中找到相交节点,为读者提供了清晰的算法实现思路。
569

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



