Find Merge Point Of Two Linked List

Node* Find_merge_point(Node *h1, Node *h2)
{
    Node *p1, *p2;
 
    int n = Length1(h1) - Length1(h2);
    if (n >= 0) {
        p1 = h1;
        p2 = h2;
    }
    else {
        n *= -1;
        p1 = h2;
        p2 = h1;
    }
 
    while (n--)
        p1 = p1->next;
 
    while (p1 != p2 && p1 != NULL && p2 != NULL) {
        p1 = p1->next;
        p2 = p2->next;
    }
 
    if (p1 == NULL || p2 == NULL) {
        printf("can't find merge point!\n");
        return NULL;
    }
    else
        return p1;
}

Time Complexity: O(m+n)
Auxiliary Space: O(1)

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License