栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 (C语言)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 (C语言)

#include
#include
#include
struct Node{
	int Data;
	struct Node *next;
};
struct Node* creat(){   
	struct Node *L;
	L=(struct Node*)malloc(sizeof(struct Node));
	L->next=NULL;
	return L;
}
void suju(struct Node *L,int n){   
	struct Node *p,*q;
	p=L;
	q=(struct Node*)malloc(sizeof(struct Node));
	while(p->next!=NULL&&p->next->Datanext;
	q->Data=n;
	q->next=p->next;
	p->next=q;
}
void print(struct Node *L){
	struct Node *p;
	p=L->next;
	while(p!=NULL){
		printf("%d ",p->Data);
        p=p->next;
	}
	printf("n");

}
struct Node* mergeTwoLists(struct Node* list1, struct Node* list2){
	struct Node *p,*q,*r,*L3;
	L3=creat();
	
	p=list1->next;
	q=list2->next;
		while(p!=NULL&&q!=NULL){     
		if(p->Data < q->Data){
			suju(L3,p->Data); 
			p=p->next;
		}
		else
		{
			suju(L3,q->Data); 
			q=q->next;
		}
	}
	if(p==NULL){
	while(q!=NULL){
		suju(L3,q->Data);
		q=q->next;
		}
	}
	else if(q==NULL){
		while(p!=NULL){
		suju(L3,p->Data);
		p=p->next;	
		}
	}
	return L3;

}
int main(){
	struct Node *L1,*L2,*L3;
	L1=creat();
	L2=creat();
	srand((int)time(NULL));
	for(int i=0;i<10;i++){
	suju(L1,rand()%100);
	suju(L2,rand()%100);
	}
	
	L3=mergeTwoLists(L1,L2);

	print(L1);
	print(L2);
	print(L3);
return 0; 
}

运行结果如下:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/779866.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号