[LeetCode] Intersection of Two Linked Lists

160. Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 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_set<ListNode*> group;
ListNode* cur = headA;
while(cur != NULL) {
group.insert(cur);
cur = cur->next;
}

cur = headB;
while(cur != NULL) {
if(group.count(cur))
return cur;
cur = cur->next;
}

return NULL;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/04/PS/LeetCode/intersection-of-two-linked-lists/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.