两个有序链表序列的合并

已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。

输入格式:

输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。

输出格式:

在一行中输出合并后新的非降序链表,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL

输入样例:

1 3 5 -1
2 4 6 8 10 -1

输出样例:

1 2 3 4 5 6 8 10
#include <stdio.h>
#include <stdlib.h>

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

struct node *creatNode();
struct node *listAdd(struct node *head_1, struct node *head_2);

int main(){
	struct node *L1 = creatNode();
	struct node *L2 = creatNode();
	struct node *L3 = listAdd(L1, L2);
	struct node *flag = L3;
	if(flag == NULL) printf("NULL");
	else{
		while(flag->Data != -1){
			printf("%d",flag->Data);
			flag = flag->Next;
			if(flag->Data != -1) printf(" ");
		}
	}
	return 0;
}


struct node* creatNode(){
	struct node *head = (struct node*)malloc(sizeof(struct node));
	struct node *flag;
	flag = head;
	scanf("%d",&flag->Data);
	while(flag->Data != -1){
		flag->Next = (struct node*)malloc(sizeof(struct node));
		flag = flag->Next;
		scanf("%d",&flag->Data);
	}
	flag->Next = NULL;
	return head;
}

struct node *listAdd(struct node *head_1, struct node *head_2){
	struct node *addHead = (struct node*)malloc(sizeof(struct node));
	struct node *addFlag = addHead;
	
	while(head_1->Data != -1 && head_2->Data != -1){
		if(head_1->Data <= head_2->Data){
			addFlag->Next = head_1; 
			head_1 = head_1->Next;
			addFlag->Next->Next = NULL;
			addFlag = addFlag->Next;
		}
		if(head_1->Data >= head_2->Data){
			addFlag->Next = head_2;
			head_2 = head_2->Next;
			addFlag->Next->Next = NULL;
			addFlag = addFlag->Next;
		}
	}
	
	if(head_1->Data != -1){
		addFlag->Next = head_1;
	}
	if(head_2->Data != -1){
		addFlag->Next = head_2;
	}
	
	addHead = addHead->Next;
	
	return addHead;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

钱墩墩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值