有序表的合并(单链表)

代码如下:

#include <stdio.h>
#include <stdlib.h>
struct LNode
{
	int data;
	struct LNode *next;
};
struct LNode a0(int i)
{
	int a,*b,c;
	b=(int*)malloc(i*sizeof(int));
	for(a=0;a<i;a++)
	{
		b[a]=rand()%10;
	}
	for(c=0;c<i;c++)
	{
		for(a=0;a<i-1;a++)
		{
			if(b[a]>b[a+1])
			{
				int d;
				d=b[a];
				b[a]=b[a+1];
				b[a+1]=d;
			}
		}
	}
	struct LNode *boy;
	boy=(struct LNode*)malloc(sizeof(struct LNode));
	boy->next=NULL;
	struct LNode *boy2;
	boy2=boy;
	int d;
	for(d=0;d<i;d++)
	{
		struct LNode *boy3;
		boy3=(struct LNode*)malloc(sizeof(struct LNode));
		boy3->data=b[d];
		boy2->next=boy3;
		boy3->next=NULL;
		boy2=boy3;
	}
	return *boy;
}
struct LNode *a2(struct LNode *a,struct LNode *b)
{
	struct LNode *c,*d,*e,*f;
	c=(struct LNode*)malloc(sizeof(struct LNode));
	c->next=NULL;
	d=a;
	e=b;
	f=c;
	while(d&&e)
	{
		if(d->data>=e->data)
		{
			f->next=e;
			e=e->next;
		}
		else
		{
			f->next=d;
			d=d->next;
		}
		f=f->next;
	}
	if(f->next==d)
	{
		f->next=e;
	}
	else
	{
		f->next=d;
	}
	return c;
}
int main(int argc, char *argv[])
{
	srand((unsigned)time(NULL));
	struct LNode *a,*a1;
	a=a0(5).next;//*创建一个有序表
	a1=a;
	while(a)
	{
		printf("%d\n",a->data);
		a=a->next;
	}
	printf("\n");
	struct LNode *b,*b1;
	b=a0(10).next;//*创建另一个有序表
	b1=b;
	while(b)
	{
		printf("%d\n",b->data);
		b=b->next;
	}
	printf("\n");
	struct LNode *c;
	c=a2(&(*a1),&(*b1))->next;//*合并两个有序表
	while(c)
	{
		printf("%d\n",c->data);
		c=c->next;
	}
	system("pause");
	return 0;
}

程序运行结果如下

0
1
1
5
8

1
2
3
3
3
5
6
7
7
9

0
1
1
1
2
3
3
3
5
5
6
7
7
8
9
请按任意键继续. . .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值