题目:设有两个非递减有序的单链表,编写算法求二者的交集(以链表形式存放),要求交集中元素保持递增有序。
分析:此题关键是要跳过相邻的重复元素。
/*
* Intersection of two non-descending linked lists.
*
* fduan, Dec. 28, 2011.
*/
void intersection( link_list lst_a, link_list lst_b, link_list * lst_i )
{
node_ptr pa = lst_a->next, pb = lst_b->next, s = NULL, p = NULL;
int e1, e2;
init_llist( lst_i );
p = *lst_i;
while( pa != NULL && pb != NULL )
{
if( pa->data < pb->data )
pa = pa->next;
else if( pa->data > pb->data )
pb = pb->next;
else
{
s = ( node_ptr )malloc( sizeof( node ) );
s->data = pa->data;
s->next = NULL;
p->next = s;
p = s;
e1 = pa->data;
e2 = pb->data;
pa = pa->next;
pb = pb->next;
while( pa != NULL && pa->data == e1 )
pa = pa->next;
while( pb != NULL && pb->data == e2 )
pb = pb->next;
}
}
}