合并两个顺序表

2.分别创建两个有序的顺序表(每个表的元素个数以及每个元素的值在运行时由键盘输入),
现将两个有序表合并,并保证新表依然为有序的顺序表。

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #define  MAXSIZE  100 
  4 typedef int DataType;
  5 
  6 typedef  struct  node 
  7 {   
  8     DataType  data[MAXSIZE];
  9      int  length;
 10 } SeqList,*PSeqList;
 11 
 12 PSeqList  Init_SeqList(void);
 13 PSeqList Input_Seqlist(PSeqList A,int *pn);
 14 PSeqList merge_SeqList (PSeqList A,  PSeqList  B,  PSeqList  C);
 15 Print_SeqList(PSeqList PL);
 16 
 17 
 18 
 19 main()
 20 {
 21     int n;
 22     PSeqList Pa,Pb,Pc;
 23     Pa=Init_SeqList();
 24     Pb=Init_SeqList();
 25     Pc=Init_SeqList();
 26     Pa=Input_Seqlist(Pa,&n);
 27     //Print_SeqList(Pa);
 28     Pb=Input_Seqlist(Pb,&n);
 29     //Print_SeqList(Pb);
 30     Pc=merge_SeqList (Pa,Pb,Pc);
 31     Print_SeqList(Pc);
 32 
 33 }
 34 
 35 PSeqList  Init_SeqList(void)
 36 {  /*创建一顺序表,入口参数无,返回一个指向顺序表的指针,指针值为零表示分配空间失败*/
 37    PSeqList  PL;
 38    PL=( PSeqList )malloc(sizeof(SeqList)); 
 39    if (PL)       /*若PL=0表示分配失败*/
 40         PL->length=0;     
 41    return (PL);
 42 } 
 43 
 44 PSeqList Input_Seqlist(PSeqList A,int *pn)
 45 {
 46     int i;
 47     printf("请输入整型数据个数:");
 48     scanf("%d",pn);
 49     printf("请输入%d个整型数据,中间用,号隔开",*pn);
 50     for(i=0;i<*pn;i++)
 51     {
 52         scanf("%d",&A->data[i]);
 53         A->length++;
 54     }
 55     return(A);
 56 
 57 }
 58 
 59 PSeqList merge_SeqList (PSeqList A,  PSeqList  B,  PSeqList  C)
 60 {    int  i,j,k;
 61       i=0;j=0;k=0;
 62       if (A->length+B->length>MAXSIZE) 
 63           {  
 64           printf("C表空间不足");      
 65           return(0);   
 66       }
 67      while ( i<A->length && j<B->length )
 68      {
 69            if (A->data[i]<B->data[j])     
 70                C->data[k++]=A->data[i++];
 71            else     
 72                C-> data[k++]=B->data[j++]; 
 73     }
 74      while (i<A->length )       
 75          C->data[k++]= A->data[i++];
 76      while (j<B->length )       
 77          C->data[k++]= B->data[j ++];
 78       C->length=k;
 79       return(C); 
 80 }   
 81 
 82 int Print_SeqList(PSeqList PL)
 83 {
 84     int i;
 85     if(!PL)
 86     {
 87         printf("无此顺序表");
 88         return -1;
 89     }
 90     if(PL->length==0)
 91     {
 92         printf("空表");
 93         return 0;
 94     }
 95 
 96     printf("顺序表的长度为%d",PL->length);
 97     printf("顺序表的各元素值为:");
 98     for(i=0;i<=PL->length-1;i++)
 99         printf("%4d",PL->data[i]);
100     return 1;
101 
102 }

 

posted @ 2017-03-20 10:54  不忘_初芯  阅读(2607)  评论(0编辑  收藏  举报