实验2.4合并两个链表,并有序排列且无重复元素

//4.将2个从小到大排列的链表,合并为一个新链表(任然有序排列),合并时去掉重复的,打印3个链表。 

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

struct Node
{
	int Data;
	struct Node *Next;
 }; 

struct Node* Create()
{
	struct Node *L;
	L=(struct Node *)malloc(sizeof(struct Node));
	L->Next=NULL;
	return L;
 } // 创建空链表,带头结点 
 
void Insert_sort(struct Node *L,int x)
{
	struct Node *p,*q;
	p=L;
	while(p->Next!=NULL&&x>p->Next->Data)
	{
		p=p->Next;
	}
	q=(struct Node *)malloc(sizeof(struct Node));
	q->Data=x;
	q->Next=p->Next;
	p->Next=q;	
}


void Print(struct Node *L){
    struct Node *q;
    q=L->Next;
    while(q!=NULL){
        printf("%d ",q->Data);
        q=q->Next;
    }
};

int main()
{
	struct Node *L1,*L2,*L3;
	L1=Create();
	L2=Create();
	L3=Create();
//	L1=(struct Node*)malloc(sizeof(struct Node));
//	L1->Next=NULL;
//	L2=(struct Node*)malloc(sizeof(struct Node));
//	L2->Next=NULL;
//	L3=(struct Node*)malloc(sizeof(struct Node));
//	L3->Next=NULL;
	srand((int)time(NULL));
	
	int i;
	for(i=0;i<10;i++)
	{
		Insert_sort(L1,rand()%100);
		Insert_sort(L2,rand()%100);
	}
	
	struct Node *a,*b;
	a=L1->Next;
	b=L2->Next;
	while(a!=NULL&&b!=NULL)
	{
		if(a->Next!=NULL&&a->Data==a->Next->Data)
		{
			a=a->Next;
		}
		else if(b->Next!=NULL&&b->Data==b->Next->Data)
		{
			b=b->Next;
		}
		else
		{	
		
				if(a->Data<b->Data)
			{
				Insert_sort(L3,a->Data);
				a=a->Next;	
			}
			else if(a->Data>b->Data)
			{
				Insert_sort(L3,b->Data);
				b=b->Next;
			}
			else
			{
				Insert_sort(L3,b->Data);
				b=b->Next;
				a=a->Next;
			}
		}
		
	}
	
	
	if(a==NULL)
		{
			while(b!=NULL)
			{
				if(b->Next!=NULL&&b->Data==b->Next->Data)
				{
					b=b->Next;
				}
				Insert_sort(L3,b->Data);
				b=b->Next;
			 } 
				
		}
	else
		{
			while(a!=NULL)
			{
				if(a->Next!=NULL&&a->Data==a->Next->Data)
				{
					a=a->Next;
				}
				Insert_sort(L3,a->Data);
				a=a->Next;
			}
			
		}
	
	Print(L1);
	printf("\n");
	Print(L2);
	printf("\n");
	Print(L3);
	return 0;
	
}
  • 7
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值