您的位置:首页 > 理论基础 > 数据结构算法

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

2011-12-24 22:14 204 查看
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 );
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐