Intersection of Linked Lists
Using set to track visited nodes
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::getIntersectionNode(ListNode* A, ListNode* B) {
set<ListNode*> s;
ListNode *ptr = A;
while(ptr) {
s.insert(ptr);
ptr = ptr -> next;
}
ptr = B;
while(ptr) {
if(s.count(ptr))
return ptr;
s.insert(ptr);
ptr = ptr -> next;
}
return NULL;
}Time Complexity: β
Space Complexity: β
Ignoring Nodes from Longer Linked List
Time Complexity: β
Space Complexity: β
Last updated