Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created May 8, 2016 18:31
Show Gist options
  • Save jianminchen/ce99505020ee58f2fd23ecd78bb2f19f to your computer and use it in GitHub Desktop.
Save jianminchen/ce99505020ee58f2fd23ecd78bb2f19f to your computer and use it in GitHub Desktop.
HackerRank - Find Merge Point of two linked list
/*
Find merge point of two linked lists
Node is defined as
struct Node
{
int data;
Node* next;
}
*/
int getLength(Node *head)
{
if(head==NULL)
return 0;
int count = 0;
while(head!=NULL)
{
head = head->next;
count++;
}
return count;
}
int FindMergeNode(Node *headA, Node *headB)
{
// Complete this function
// Do not write the main method.
int len1 = getLength(headA);
int len2 = getLength(headB);
int longerOne=len1>=len2?len1:len2;
int shortOne =len1<len2?len1:len2;
if(len1< len2)
{
Node* tmp = headA;
headA = headB;
headB = tmp;
}
// headA longer one
for(int i=0;i<longerOne - shortOne; i++)
{
headA = headA->next;
}
for(int i=0; i<shortOne; i++)
{
if(headA->data == headB->data)
return headA->data;
headA = headA->next;
headB = headB->next;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment