Intersection of Two Linked Lists
https://leetcode.com/problems/intersection-of-two-linked-lists/
brute force:
start with link list 1 : check if that node is same as all other nodes of linklist 2;
traverse for all nodes of linklist 1
2nd solution :
use hash map
traverse and hash the address of the one linklist:
then for the second linklist if the address match any of the address of the hash , then that node is ans
3rd solution:
create 2 dummy node:
find the length of both the linklist
subtract the length of long -short
move the node of long by the subtracted ans
then traverse both the dummy node to find where the node matches
4th solution:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==NULL || headB==NULL) return NULL;
ListNode *a=headA;
ListNode *b=headB;
while(a!=b){
a= a==NULL? headB : a->next;
b= b==NULL? headA : b->next;
}
return a;
}
};
Comments
Post a Comment