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

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
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->Data<n)
		p=p->next;
	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; 
}

运行结果如下:

  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值