Skip to content

Commit 2046988

Browse files
authored
Create solution.cpp
1 parent d242d1d commit 2046988

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
12+
{
13+
auto curNodeA = headA;
14+
auto curNodeB = headB;
15+
16+
// Map the number of times each node is visited
17+
unordered_map<ListNode*, int> nodeVisitCount;
18+
19+
while (curNodeA != nullptr || curNodeB != nullptr)
20+
{
21+
// Add nodes to map to keep track of visited nodes
22+
// And also check for intersected nodes
23+
24+
if (curNodeA != nullptr)
25+
{
26+
if (++nodeVisitCount[curNodeA] > 1)
27+
return curNodeA;
28+
}
29+
30+
if (curNodeB != nullptr)
31+
{
32+
if (++nodeVisitCount[curNodeB] > 1)
33+
return curNodeB;
34+
}
35+
36+
// iterate to next nodes to continue search
37+
38+
if (curNodeA != nullptr)
39+
curNodeA = curNodeA->next;
40+
41+
if (curNodeB != nullptr)
42+
curNodeB = curNodeB->next;
43+
}
44+
45+
// if we reached here then no intersection node was found
46+
return nullptr;
47+
}
48+
};

0 commit comments

Comments
 (0)