#pragma warning(disable:4996)
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(STU)
typedef struct stu
{
int num;
int score;
struct STU* next;
}STU;
int main()
{
STU *creat();
STU* insert(STU * ah, STU * bh);
void print(STU *abh);
STU* ahead, * bhead, *abh;
printf("请输入第一组链表:\n");
ahead = creat();
print(ahead);
printf("请输入第二组链表:\n");
bhead = creat();
print(bhead);
#if(1)
abh = insert(ahead, bhead);
printf("合并后的链表为:\n");
print(abh);
#endif
}
//创建链表的部分
STU* creat()
{
STU* head, * p1, * p2;
int n;
head = NULL;
p2 = p1 = (STU*)malloc(LEN);
printf("请输入学号和成绩,以学号为0结束:\n");
scanf("%d %d", &p1->num, &p1->score);
while (p1->num != 0)
{
if (head == NULL)
{
head = p1;
}
else
{
p2 = p1;
p1 = (STU*)malloc(LEN);
scanf("%d %d", &p1->num, &p1->score);
p2->next = p1;
}
}
p1->next = NULL;
return head;
}
void print(STU* abh)
{
printf("NUM Score\n");
do
{
printf("%-11d %-11d\n", abh->num, abh->score);
abh = abh->next;
} while (abh->next != NULL);
return 0;
}
STU* insert(STU* ah, STU* bh)
{
STU* pa1, * pa2, * pb1, * pb2;
pa2 = pa1 = ah;
pb2 = pb1 = bh;
do
{
while (pb1->num > pa1->num && pa1->next != NULL)
{
pa2 = pa1;
pa1 = pa1->next;//若当前B组两个指针指向的的num 大于 A组尾部num,则将A组两个指针平移
}
if (pb1->num < pa1->num)//当出现B组两个指针指向的num小于A组尾部时。。。
{
if (pa1 == ah)//若为A组头指针大于B组头指针,则直接将A组头指针指向B组开头
{
ah = pb1;
}
else
{ //pa1,pa2分别指向A组中一前一后两个元素
pa2->next = pb1;
pb1 = pb1->next;
pb2->next = pa1;
pa2 = pb2;
pb2 = pb1; //pb1=pb2,即B组两个指针在开始比较之前总是指向同一个元素
}
}
} while ((pa1->next != NULL) || (pb1->num > pa1->num && pb1 != NULL));
if ((pb1 != NULL) && (pb1->num > pa1->num) && (pa1->next == NULL))//当A组两个指针指向了最后两个指针,且B组两个指针不指向空,这直接首尾相连
{
pa1->next = pb1;
}
return ah;
}
C语言学习---输入两个有序链表,合并两个有序链表并重新排序
最新推荐文章于 2022-11-07 14:27:38 发布