File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
IntersectionOfTwoLinkedLists Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments