C/C++ code#include
#include
#include
//#define NULL 0 没有必要
struct student
{
int num; //学号
int score; //分数
struct student *next; //下一结点
};
struct student *creat(void)
{
struct student *p1,*p2,*head;
int n=0;
p1 = p2 = (struct student *)malloc(sizeof(struct student)); //创建头结点
head= NULL;
printf("\n请输入学号与分数,以0结束输入!\n");//最好要有输入提示
scanf("%d,%d",&p1->num,&p1->score);
while (p1->num!=0) //输入0 结束
{
n=n+1;
if(n==1) //判断头结点
head=p1;
else
p2->next=p1;
p2=p1; //保存前驱结点
p1=(struct student *)malloc(sizeof(struct student)); //开辟新的结点
scanf("%d,%d",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}
struct student *insert(struct student *head,struct student *pi) //插入结点
{
struct student *pf,*pb;
pb=pf=head;
if(head==NULL) //空链表 插入
{
head=pi;
head->next=NULL;
return head;
}
while((pb->next!=NULL)&&(pb->numnum)) //比较大小 按顺序插入
{
pf=pb;
pb=pb->next;
}
if(pb->num>=pi->num) //找到了所要插入的位置 (从小到大)
{
if(pb==head) //插入到 链表 的 头
{
head=pi;
pi->next=head;
}
else
{ //插入到普通位置
pf->next=pi;
pi->next=pb;
}
}
else //插入到链表的 尾
{
pb->next=pi;
pi->next=NULL;
}
return head;
}
struct student *sort(struct student *heada,struct student *headb)// 若链表a是有序的 插入排序
{
struct student *pb,*pb1;
pb = pb1 = headb;
if((heada == NULL)&&(headb != NULL))
{
heada = headb;
}
else if((headb == NULL)&&(heada != NULL))
{
headb = heada;
}
else
{
while(pb1!= NULL) //控制listb,将listb中的结点依次插入lista中
{
pb = pb1;
pb1 = pb1->next;
heada=insert(heada,pb);
}
}
return heada;
}
void print(struct student *head)
{
struct student *p;
p=head;
while(p!=NULL)
{
printf("%d,%d\n",p->num,p->score);
p=p->next;
}
}
int main(int argc,char *argv[])
{
struct student *heada,*headb,*pb;
printf("input the list a:");
heada=creat(); //创建链表a
print(heada);
printf("\ninput the list b:");
headb=creat(); //创建链表b
print(headb);
printf("\nthe new list :\n");
pb = sort(heada,headb); //升序合并链表a和b
print(pb);
}