王道p40 13.假设有两个按元素值递增次序排列的线性表,均以单链表形式存储。请编写算法将这两个单链表归并为一个按元素值递减次序排列的单链表,并要求利用原来两个单链表的结点存放归并后的单链表。

本体代码如下

void hebing(linklist* A, linklist* B)
{
	lnode* r, * pa = (*A)->next, * pb = (*B)->next;
	(*A)->next = NULL;
	while (pa && pb)//当两个链表都不为空时
	{
		if (pa->data <= pb->data)
		{
			r = pa->next;//r暂存pa的后继节点指针
			pa->next = (*A)->next;//头插法一次插入到A中
			(*A)->next = pa;
			pa = r;//使pa恢复为当前待比较的结点
		}
		else
		{
			r = pb->next;
			pb->next = (*A)->next;
			(*A)->next = pb;
			pb = r;
		}
}
		if (pa)//通常情况会剩下一个链表非空
			pb = pa;
		while (pb)
		{
			r = pb->next;
			pb->next = (*A)->next;
			(*A)->next = pb;
			pb = r;
		}
	free(*B);
}

完整测试代码

#include
#include
typedef struct lnode
{
	int data;
	struct lnode* next;
}lnode,*linklist;
int n = 5;
int a[5] = { 1,3,5,7,9 };
int b[5] = { 2,4,6,8,10 };
void buildlinklist(linklist* L,int arr[],int n)
{
	*L = (lnode*)malloc(sizeof(lnode));
	(*L)->next = NULL;
	lnode* s = *L, * r = *L;
	int i = 0;
	for (i = 0; i < n; i++)
	{
		s = (lnode*)malloc(sizeof(lnode));
		s->data = arr[i];
		s->next = r->next;
		r->next = s;
		r = s;
	}
	r->next = NULL;
}
void hebing(linklist* A, linklist* B)
{
	lnode* r, * pa = (*A)->next, * pb = (*B)->next;
	(*A)->next = NULL;
	while (pa && pb)//当两个链表都不为空时
	{
		if (pa->data <= pb->data)
		{
			r = pa->next;//r暂存pa的后继节点指针
			pa->next = (*A)->next;//头插法一次插入到A中
			(*A)->next = pa;
			pa = r;//使pa恢复为当前待比较的结点
		}
		else
		{
			r = pb->next;
			pb->next = (*A)->next;
			(*A)->next = pb;
			pb = r;
		}
}
		if (pa)//通常情况会剩下一个链表非空
			pb = pa;
		while (pb)
		{
			r = pb->next;
			pb->next = (*A)->next;
			(*A)->next = pb;
			pb = r;
		}
	free(*B);
}
void print(linklist* L)
{
	lnode* p = (*L)->next;
	while (p)
	{
		printf("%d ", p->data);
		p = p->next;
	}
}
int main()
{
	linklist A, B;
	buildlinklist(&A, a, n);
	buildlinklist(&B, b, n);
	printf("单链表A为:");
	print(&A);
	printf("\n单链表B为:");
	print(&B);
	hebing(&A, &B);
	printf("\n合并后的单链表为:");
	print(&A);

你可能感兴趣的:(王道课后习题单链表,算法,数据结构,c语言)