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

源代码:

#include <stdio.h>
#define NULL 0
#define LEN sizeof(struct student)

struct student
{
 long num;
 int score;
 struct student* next;
};

struct student listA,listB;
int n,sum=0;

int main()
{
 struct student *creat();
 struct student *insert();
 void print();
 struct student * ahead,*bhead,*abh;
 ahead=creat();
 sum=n;
 bhead=creat();
 sum=sum+n;
 abh=insert(ahead,bhead);
 print(abh);
}

struct student *creat()
{
 struct student *p1,*p2,*head;
 n=0;
 p1=p2=(struct student*)malloc(LEN);
 printf("请输入学生的学号和成绩:\n");
 printf("如果输入的学号为0,则停止输入\n");
 scanf("%ld,%ld",&p1->num,&p1->score);
 head=NULL;
 while(p1->num!=0)
 {
  n=n+1;
  if(n==1)
   head=p1;
  else
   p2->next=p1;
  p2=p1;
  p1=(struct student*)malloc(LEN);
  printf("请输入学生的学号和成绩:\n");
  scanf("%ld,%ld",&p1->num,&p1->score);
 }
 p2->next=NULL;
 return head;
}

struct student *insert(struct student* ah,struct student* bh)
{
 struct student *pa1,*pa2,*pb1,*pb2;
 pa2=pa1=ah;
 pb2=pb1=bh;
 if(pa1==NULL) //如果listA为空,则直接返回listB
  return(bh);
 if(pb1==NULL)
  return(ah);
  while ((pb1!=NULL)&&((pb1->next!=NULL)||(pa1->next!=NULL))) //pb1!=NULL 要写在pb1->next!=NULL前面,因为若pb1=NULL,则pb1.next不存在,而判断pb1->next!=NULL时会出错。A&&B。先判断第一项A,第一项A为假,就不再判断B。
 {
  while((pb1->num>pa1->num)&&pa1->next!=NULL)
  {
   pa2=pa1;
   pa1=pa1->next;
  }
  if(pb1->num<=pa1->num)
  {
   if(pa1==ah)
    ah=pb1;
   else
    pa2->next=pb1;//
   pa2=pb1;
   pb1=pb1->next;
   pb2->next=pa1;
   
  }
  else //pb1->num比A链中的任何num都大,要排到A链的最后
  {
   pa1->next=pb1;//
   pb1=pb1->next;//依次按序pb1取B链的各个节点值
   pb2->next=NULL;//A链的末尾最后一个元素—>nest=NULL;
   pa1=pa1->next;//pa1指向A链的末尾
  }

   //pb1=pb2->next;//
   //pb2->next=pa1;//
   //pa2=pb2;
   pb2=pb1;//以便 上面的代码 pb2->next=pa1;

 } 
 
 if(pb1!=NULL&&(pb1->num>pa1->num)&&pa1->next==NULL) //pb1!=NULL&&pb1->next==NULL&&pa1->next==NULL时
  pa1->next=pb1;

 return(ah);
}


void print(struct student* head)
{
 struct student* p;
 printf("\n共有%d条记录,它们是:\n",sum);
 p=head;
 if(p!=NULL)
 {
  do
  {
   printf("%ld %d\n",p->num,p->score);
   p=p->next;
  } while (p!=NULL);
 }
}