Skip to content

Instantly share code, notes, and snippets.

@umang94
Last active August 29, 2015 14:04
Show Gist options
  • Save umang94/10e0de8262a275e9cc89 to your computer and use it in GitHub Desktop.
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
/*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;
}
@umang94
Copy link
Author

umang94 commented Aug 19, 2014

Comparing the node addresses instead of the node data covers the case of Linked Lists having non unique elements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment