程序功能:输入若干个学生成绩(输入-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;
}