#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
typedef struct stu{
int id; //学号
char sex[10]; //性别
float score; //成绩
struct stu *next; //下一节点的头指针
} STU;
STU *create(){
STU *p1,*p2,*head;
int n=0;
p1 = p2 = (STU*)malloc(sizeof(STU));
scanf("%d,%f,%s",&p1->id,&p1->score,&p1->sex);
head = NULL;
while(p1->id != 0){
n++;
if(n == 1)
head = p1; //把第一个节点指针赋值给头指针
else
p2->next = p1; //如果是第2.....n个节点 把新分配的p1地址赋值给当前节点的下一个指针元素
p2 = p1; //当前节点指针同步到新的分配内存地址
p1 = (STU*)malloc(sizeof(STU)); //分配新的内存空间
scanf("%d,%f,%s",&p1->id,&p1->score,&p1->sex);
}
p2->next = NULL; //跳出循环后当前节点的下一头指针值为NULL
return head;
}
/**
* 移动指针操作
*/
void MoveNode(STU** destRef, STU** sourceRef)
{
/* the front source node */
STU* newNode = *sourceRef;
assert(newNode != NULL);
/*Advance the source pointer */
*sourceRef = newNode->next;
/* Link th eold dest off the new node */
newNode->next = *destRef;
/*Move dest to point to the new node */
*destRef = newNode;
}
STU* SortedMerge(STU* a, STU* b)
{
STU* result = NULL;
/*point to the last result pointer */
STU** lastPtrRef = &result;
while(1)
{
if(a == NULL)
{
*lastPtrRef = b;
break;
}
else if(b == NULL)
{
*lastPtrRef = a;
break;
}
if(a->id <= b->id)
{
MoveNode(lastPtrRef, &a);
}
else
{
MoveNode(lastPtrRef, &b);
}
/*tricky:advance to point to the next ".next" field */
lastPtrRef = &((*lastPtrRef)->next);
}
return (result);
}
int main() {
STU *p,*psed,*new,*po,*pl;
p = create(); //新建一个链表
psed = create(); //新建第二个链表
po = p;
pl = psed;
printf("第一个链表:\n");
while(1){
printf("%d\t%s\t%0.2f\n",p->id,p->sex,p->score);
p=p->next;
if(p == NULL)
break;
}
printf("第二个链表:\n");
while(1){
printf("%d\t%s\t%0.2f\n",psed->id,psed->sex,psed->score);
psed=psed->next;
if(psed == NULL)
break;
}
printf("\n");
new = SortedMerge(po,pl);
printf("合并的链表:\n");
while(1){
printf("%d\t%s\t%0.2f\n",new->id,new->sex,new->score);
new=new->next;
if(new == NULL)
break;
}
return EXIT_SUCCESS;
}
【C语言】合并,排序两个链表
最新推荐文章于 2022-11-07 14:27:38 发布