题:将a,b两个链表连接起来并按升序排列。
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct Student)
struct Student
{
long num;
int score;
struct Student* next;
};
int main()
{
struct Student* Creat_List(void);
struct Student* Insert(struct Student* ahead, struct Student* bhead);
void Print(struct Student* ahead);
struct Student* ahead, * bhead, * abhead;
printf("list a:\n");
ahead = Creat_List();
printf("list b:\n");
bhead = Creat_List();
abhead = Insert(ahead, bhead);
Print(abhead);
return 0;
}
struct Student* Creat_List(void)
{
int n = 0;
struct Student* p1, * p2, * head=NULL;
p1 = p2 = (struct Student*)malloc(LEN);
scanf_s("%ld %d", &p1->num, &p1->score);
while (p1->num != 0)
{
n = n + 1;
if (n == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = (struct Student*)malloc(LEN);
scanf_s("%ld %d", &p1->num, &p1->score);
}
p2->next = NULL;
return head;
}
struct Student* Insert(struct Student* ahead, struct Student* bhead)
{
struct Student* pa1, * pa2, * pb1, * pb2;
pa1 = pa2 = ahead;
pb1 = pb2 = bhead;
do
{
while ((pa1->num < pb1->num) && (pa1->next != NULL))
{
pa2 = pa1;
pa1 = pa1->next;
}
if (pa1->num >= pb1->num)
{
if (pa1 == ahead)
ahead = pb1;
else
pb2->next = pb1;
pb1 = pb1->next;
pb2->next = pa1;
pa2 = pb2;
pb2 = pb1;
}
} while ((pa1->next != NULL) || (pa1 == NULL && pb1 != NULL));
if ((pb1 != NULL) && (pb1->num > pa1->num) && (pa1->next == NULL))
pa1->next = pb1;
return ahead;
}
void Print(struct Student* ahead)
{
struct Student* p;
p = ahead;
while (p != NULL)
{
printf("%ld %d\n", p->num, p->score);
p = p->next;
}
}
结果为什么这样了?
另外:有无hxd梳理一下它这个Insert函数的思路,大脑有点混乱。尤其没明白那个do.while.循环条件。