数据结构题典001:有序线性表的归并(ANSI C)

1、有序顺序表的归并排序,假设a[0] <= a[1] <= ... <= a[n-1]

void merge_list( int a[], int m, int b[], int n, int ** c )
{
	int i = 0, j = 0;
	int *pa = a, *pb = b, *pc = NULL, *qa = a + m - 1, *qb = b + n - 1;
	
	if( *c != NULL )
		free( *c );
	
	*c = ( int * )malloc( sizeof( int ) * ( m + n ) );
	assert( *c != NULL );
	pc = *c;
	
	while( pa <= qa && pb <= pb )
		*pc++ = ( *pa <= *pb ) ? *pa++ : *pb++;
	
	while( pa <= qa )
		*pc++ = *pa++;

	while( pb <= qb )
		*pc++ = *pb++;
}
2、有序单链表的归并排序,假设a[0] <= a[1] <= ... <= a[n-1]

typedef int elem_type;

struct node;
typedef struct node node;
typedef node * node_ptr;
typedef node * link_list;

struct node
{
	elem_type data;
	node_ptr next;
};

void merge_list( link_list * lst_a, link_list * lst_b, link_list * lst_c )
{
	node_ptr pa = (*lst_a)->next, pb = (*lst_b)->next, pc;
	*lst_c = pc = *lst_a;
	while( pa != NULL && pb != NULL )
	{
		if( pa->data <= pb->data )
		{
			pc->next = pa; pc = pa; pa = pa->next;
		}
		else
		{
			pc->next = pb; pc = pb; pb = pb->next;
		}
	}

	pc->next = ( pa == NULL ) ? pb : pa;
	free( *lst_b );
}


你可能感兴趣的:(数据结构题典001:有序线性表的归并(ANSI C))