pta-7-51(合并两个有序链表)

本题属于一道水题,但有几个地方地思想还是值得好好体会,一是在合并时采用带头结点的链表避免讨论新链表的头的指向问题,二是相对于网上其他的题解来说,本题解更加简洁。欢迎各位交流学习。

#include
#include
typedef struct List
{
  int data;
  struct List *next;
}node, * list;
list  READ(void);
list MERGE(list s1,list s2);
void PRINT(list s3);
int main()
{
  list s1,s2,s3;
  s1=READ();
  s2=READ();
  s3=MERGE(s1,s2);
  PRINT(s3);
  return 0;
}
list READ(void)
{
  list p,r,head=NULL;
  int i;
  scanf("%d",&i);
  while(i != -1){
      p=(list)malloc(sizeof(node));
      p->data = i;
      p->next = NULL;
      if(head){
          r->next = p;
          r = p;
      }
      else{
          head = p;
          r = p;
      }
      scanf("%d",&i);
  }
  return head;
}
list MERGE(list s1,list s2)
{                                
  list s3,a=s1,b=s2,r;
  s3=(list)malloc(sizeof(node));                    //创建头结点
  s3->next=NULL;
  r = s3;
  while(a&&b){
     if(a->data<=b->data){
         r ->next= a;
         r = a;
         a = a->next;
     }
     else{
         r->next = b;
          r = b;
          b = b->next;
     }
  }
   r->next = a? a: b;
  return s3;
  
}
void PRINT(list s3)
{
  list p = s3->next;
  if(!p)
  printf("NULL\n");
  while(p)
  {
      if(p->next)
      printf("%d ",p->data);
      else
      printf("%d",p->data);
    p=p->next;
  }
}



你可能感兴趣的:(pta-7-51(合并两个有序链表))