Last active
August 29, 2015 14:04
-
-
Save umang94/10e0de8262a275e9cc89 to your computer and use it in GitHub Desktop.
A simple function to find the merge point of two Linked Lists in O(n) time and O(1) space
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Make an interating pointer that goes forward every time till the end, and then jumps to the beginning of the opposite list, and so on. Create two of these, pointing to two heads. Advance each of the pointers by 1 every time, until they meet.*/ | |
int FindMergeNode(Node *headA, Node *headB) | |
{ | |
Node *p1 = headA; | |
Node *p2 = headB; | |
while(p1 != p2){ | |
p1 = p1->next; | |
p2 = p2->next; | |
if(p1 == NULL) | |
p1 = headB; | |
if(p2 == NULL) | |
p2 = headA; | |
} | |
return p1->data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Comparing the node addresses instead of the node data covers the case of Linked Lists having non unique elements.