試編寫一個算法,將兩個有序線性表合成一個有序線性表...最好是在c++上可以直接運行出來的

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
typedef int ElemType;
#define INITSIZE 100

typedef struct
{
 ElemType *data;
 int length;
 int listsize;
}sqlist;

/*初始化*/
void initlist(sqlist *L,int n)
{
 int i;
 L->data =(ElemType *)malloc(sizeof(ElemType)*INITSIZE);
 L->length=0;
 for(i=1;i<=n;i++)
 {
 scanf("%d",&L->data[i-1]);
 L->length++;
 }
 L->listsize=INITSIZE;
}

/*插入元素*/
int insert(sqlist *L,int i,ElemType x)
{
 int j;
 if(i<1||i>L->length+1) return 0;
 if(L->length==L->listsize) //存儲空間不夠,增加一個
 {
  L->data=(ElemType *)realloc(L->data,(L->listsize+1)*sizeof(ElemType));
  L->listsize++; //重置存儲空間長度
 }
 for(j=L->length;j>=i;j--) 
  L->data[j]=L->data[j-1]; //將序號爲i的結點及之後的結點後移
 L->data[i-1]=x; //在序號爲i處放入x
 L->length++;

return 1;
} 
/*歸併 增序*/
void merge(sqlist A, sqlist B, sqlist *C)
{
 int m =0, n=0;
 while (m < A.length && n<B.length)
  if(A.data[m]<B.data[n]) //將A的data[m]插入C尾部
  {
   insert(C,C->length+1,A.data[m]); 
   m++;
  }
  else //將B的data[n]插入C尾部
  {
   insert(C,C->length+1,B.data[n]); 
   n++;
  }

while(m<A.length) //B完,將A的剩餘部分插入C
 {
  insert(C,C->length+1,A.data[m]); 
  m++;
 }
 while(n<B.length) //A完,將B的剩餘部分插入C
 {
  insert(C,C->length+1,B.data[n]); 
  n++;
 }
}

/*歸併 逆序*/
void merge1(sqlist A, sqlist B, sqlist *C)
{
 int m =0, n=0;
 while (m < A.length && n<B.length)
  if(A.data[m]<B.data[n]) //將A的data[m]插入C頭部
  {
   insert(C,1,A.data[m]); 
   m++;
  }
  else //將B的data[n]插入C頭部
  {
   insert(C,1,B.data[n]); 
   n++;
  }

while(m<A.length) //B完,將A的剩餘部分插入C
 {
  insert(C,1,A.data[m]); 
  m++;
 }
 while(n<B.length) //A完,將B的剩餘部分插入C
 {
  insert(C,1,B.data[n]); 
  n++;
 }
}

/*輸出*/
void list(sqlist *L)
{
 int i;
 for(i=0;i<L->length;i++)
  printf("%d ",L->data[i]);
 printf("\n");
}

/*主函數*/
void main()
{
 int m=0,n=0;
 sqlist A,B,C;
 printf("please input the number of A elemtype M is:");
 scanf("%d",&m);
 initlist(&A,m);
 printf("please input the number of B elemtype N is:");
 scanf("%d",&n);
 initlist(&B,n);
 printf("merge A and B is C:\n");
 C.data =(ElemType *)malloc(sizeof(ElemType)*INITSIZE);
 C.length=0;
 C.listsize=INITSIZE;
 merge1(A,B,&C);
 list(&C);

}
 
以上是在VC6.0上運行通過的。 
//運行結果:
 
please input the number of A elemtype M is: 3
3 5 6
please input the number of B elemtype N is: 5
1 4 6 8 9

merge A and B is C:
9 8 6 6 5 4 3 1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章