Given two linked lists, which merge at some point, find the point at which they merge
Use hash table to record all node addresses of list 1, traverse list 2 to look up the first common node on the hash table
Or
Get the length of first list and length of second list, get the difference k between two length, forward the pointer of longer list to the kth node. Compare two pointers, if same, this is the merge point, else forward to the next node, until reach the last node.
list* foo(list* head1, list* head2)
{
if(!head1||!head2) return NULL;
int h1=h2=0;
list* p1=head1;
list* p2=head2;
while(p1)
{p1=p1->next;h1++;}
while(p2)
{p2=p2->next;h2++;}
p1=head1;p2=head2;
while(h1>h2)
{p1=p1->next;h1--;}
while(h2>h1)
{p2=p2->next;h2--;}
while(p1!=p2)
{p1=p1->next;p2=p2->next;}
return p1;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment