[Oracle] LeetCode 160 Intersection of Two Linked Lists
Given the heads of two singly linked-lists headA
and headB
, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null
.
Solution
我们直接用 \(map\) 来保存 \(ListNode*\) 是否存在。
点击查看代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
unordered_map<ListNode*,int> mp;
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
while(headA){
mp[headA]=1;
headA=headA->next;
}
while(headB){
if(mp[headB])return headB;
headB = headB->next;
}
return NULL;
}
};