寻找两个单链表的第一个公共节点

class List { public: int v; List *next; List():v(0), next(0){} }; List * find_first_cross(List *h1, List *h2) { if(!h1 || !h2) return 0; int len1 = 0, len2 = 0; List *p = h1; while(p) { ++len1; p = p->next; } p = h2; while(p) { ++len2; p = p->next; } if(len1 >= len2) { int remain = len1 - len2; while(remain--) h1 = h1->next; } else { int remain = len2 - len1; while(remain--) h2 = h2->next; } while(h1 && h2 && h1 != h2) { h1 = h1->next; h2 = h2->next; } if(!h1 || !h2) return 0; else return h1; }

你可能感兴趣的:(寻找两个单链表的第一个公共节点)