C语言合并两个已按升序排序链表

程序功能:输入若干个学生成绩(输入-1为结束标志),建立两个已按升序排序的单向链表,头指针分别为list1、list2,把两个链表拼成一个升序排序的新链表,并输出新链表信息。要求自定义函数,实现将两个链表拼成一个链表,并返回拼组后的新链表。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct student {
	double score;
	struct student* next;
}student;
typedef student* node;
node initi_list(node head)  //初始化链表
{
	double a=0;
	node pNew = (node)malloc(sizeof(student));
	node p;
	while (1) {
		if (a == -1)
			printf("至少输入一个正常数据!\n");
		scanf("%lf", &a);
		if (a != -1)
			break;
	}
	pNew->score = a;
	pNew->next = NULL;
	head = pNew;
	p = head;
	while (1)
	{
		 pNew = (node)malloc(sizeof(student));
		 scanf("%lf", &a);
		 if (a == -1)
		 {
			 free(pNew);
			 break;
		 }
		 pNew->score = a;
		 pNew->next = NULL;
		 p->next = pNew;
		 p = pNew;
	}
	return head;
}
void show_list(struct student* head)  //输出所有信息
{
	struct student* p;
	if (head == NULL)
	{
		printf("无学生信息\n");
	}
	else
	{
		for (p = head; p->next!=NULL; p = p->next)
			printf("%.2lf ", p->score);
		printf("%.2lf\n", p->score);
	}
}
node combine(node p1, node p2)  //链表合并
{
	node p3=NULL;
	node head = NULL;
	while (p1 != NULL || p2 != NULL)
	{
		node pNew = (node)malloc(sizeof(student));
		if (p1!=NULL && p2!=NULL)  //都还有数据
		{
			if(p1->score>p2->score)  //p2小
			{
				pNew->score = p2->score;
				p2 = p2->next;
			}
			else {
				pNew->score = p1->score;  //p1小
				p1 = p1->next;
			}
		}
		else if (p1 == NULL)  //p1没数据了
		{
			pNew->score = p2->score;
			p2 = p2->next;
		}
		else  //p2没数据了
		{
			pNew->score = p1->score;
			p1 = p1->next;
		}
		if (p3 == NULL)  //p3头结点的初始化,这部分正常只会执行一次
		{
			head = pNew;
			p3 = head;
			p3->next = NULL;
		}
		else  //p3非头结点
		{
			p3->next = pNew;
			p3 = pNew;
			p3->next = NULL;
		}
	}
	return head;  //注意要返回头结点
}

int main()
{
	node p1 = NULL;
	node p2 = NULL;
	node p3 = NULL;
	printf("输入第一组学生成绩:\n");
	p1 = initi_list(p1);
	printf("输入第二组学生成绩:\n");
	p2 = initi_list(p2);
	printf("合并后的成绩:\n");
	p3 = combine(p1, p2);
	show_list(p3);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值