已有a,b两个链表,每个链表中的结点包括学号,成绩。要求把两个链表合并,按学号升序排列。

来源:互联网 发布:淘宝创业必备知识 编辑:程序博客网 时间:2024/06/05 07:06
#include <stdio.h>#include <stdlib.h>#define LEN sizeof(struct student)#define NULL 0int n=0;struct student {int num;char name[10];struct student *next;};struct student *creat(void){                        //创建链表函数struct student *head,*p1,*p2;p1=p2=(struct student *)malloc(LEN);head=NULL;scanf("%d %s",&p1->num,p1->name);while(p1->num!=0){        n++;if(n==1){head=p1;}    else p2->next=p1;            p2=p1;            p1=(struct student *)malloc(LEN);            scanf("%d %s",&p1->num,p1->name);    }        p2->next=NULL;        n=0;        return head;}struct student *ronghe(struct student *p1,struct student *p2){   //链表合并函数struct student *p=p1;while(p1->next!=NULL) p1=p1->next;   p1->next=p2;return p;}void paixu(struct student *p){                                  //链表排序函数                                          char tname[20]; int tnum,k=0,i=1; struct student *p1; p1=p; while(i!=0)    {        while(p1->next!=NULL){                if(p1->num>p1->next->num)  {                    tnum=p1->num;                    p1->num=p1->next->num;                    p1->next->num=tnum;                    strcpy(tname,p1->name);                    strcpy(p1->name,p1->next->name);                    strcpy(p1->next->name,tname);                    k++;                }                p1=p1->next;            }            p1=p;        if(k>0){k=0;}        else i=0;    }}void print(struct student *p){                                  //打印链接函数while(p!=NULL){    printf("%d %s\n",p->num,p->name);    p=p->next;}}int main(){struct student *p1=creat();struct student *p2=creat();struct student *p=ronghe(p1,p2);paixu(p);print(p);}

阅读全文
0 0
原创粉丝点击