题目:与009类似,但这次是求并集。
分析:与有序顺序表归并思路类似,只是注意要处理两个顺序表当前指针指向的元素相同的情形(此时只为并集中增加一项)。
/*
* Union set of two linked lists which have non-descending order.
*
* fduan, Dec. 28, 2011.
*/
void calc_union( link_list lst_a, link_list lst_b, link_list * lst_u )
{
node_ptr pa = lst_a->next, pb = lst_b->next, s = NULL, p = NULL;
init_llist( lst_u );
p = *lst_u;
while( pa != NULL && pb != NULL )
{
s = ( node_ptr )malloc( sizeof( node ) );
s->next = NULL;
if( pa->data < pb->data )
{
s->data = pa->data; pa = pa->next;
}
else if( pa->data > pb->data )
{
s->data = pb->data; pb = pb->next;
}
else
{
s->data = pa->data; pa = pa->next; pb = pb->next;
}
p->next = s;
p = s;
}
while( pa != NULL )
{
s = ( node_ptr )malloc( sizeof( node ) );
s->next = NULL;
s->data = pa->data;
p->next = s;
p = s;
pa = pa->next;
}
while( pb != NULL )
{
s = ( node_ptr )malloc( sizeof( node ) );
s->next = NULL;
s->data = pb->data;
p->next = s;
p = s;
pb = pb->next;
}
}