两种链表的合并运算(一种带头结点的,一种不带头结点)

二:不带头结点的两个链表的合并

#include

#include

typedefint ElemType;

typedefstruct LNode{

         int data;

         struct LNode *next;

}LNode,*LinkList;

 void  create(LinkList &La,int n)

{

         int i;

         LNode *p,*q;

         La=(LinkList)malloc(sizeof(LNode));

      La->next=NULL;

         p=(LinkList)malloc(sizeof(LNode));

         scanf("%d",&p->data);

         p->next=NULL;

         La=p;

         for(i=n-1;i>0;--i){

                   q=(LinkList)malloc(sizeof(LNode));

                   scanf("%d",&q->data);

                   p->next=q;

                   p=q;

                   q->next=NULL;

         }

}

 

 

LinkList   Merge(LinkList &La,LinkList &Lb){

         LinkList Lc;

         LNode *pa,*pb,*pc;

         pa=La;pb=Lb;

         Lc=pc=La;

         if(pa->datadata){

                   pc=pa;pa=pa->next;}

         else if(pa->next==pb->next){

                   pc=pa;pa=pa->next;pb=pb->next;}

         else{

                   pc=pb;pb=pb->next;

         }

         while(pa&&pb)

         {

                   if(pa->datadata){

                            pc->next=pa;pc=pa;pa=pa->next;}

                   elseif(pa->data==pb->data){

                            pc->next=pa;pc=pa;pa=pa->next;pb=pb->next;}

                   else{

                            pc->next=pb;pc=pb;pb=pb->next;

                   }

}

         pc->next=pa?pa:pb;

         return Lc;

        

}

 

 

void   main()

{

         LinkList La,Lb,Lc;

         LNode *pc,*pa,*pb;

         int n;

         printf("请输入链表LA的表长:");

    scanf("%d", &n);

         printf("请输入链表LA:");

         create(La,n);

         printf("请输入链表LB的表长:");

         scanf("%d", &n);

         printf("请输入链表LB:");

         create(Lb,n);

         pa=La;

         pb=Lb;

         printf("链表LA:");

         while(pa!=NULL){

                   printf("%d",pa->data);

                   pa=pa->next;

         }

         printf("\n");

         printf("链表LB:");

         while(pb!=NULL){

                   printf("%d",pb->data);

                   pb=pb->next;

         }

         printf("\n");

        

         Lc=Merge(La,Lb);

         pc=Lc;

         printf("合并后链表Lc:");

         while(pc!=NULL){

                   printf("%d",pc->data);

                   pc=pc->next;

         }

         printf("\n");

}


你可能感兴趣的:(C数据结构)