#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
试编写一个算法,将两个有序线性表合成一个有序线性表...最好是在c++上可以直接运行出来的
最新推荐文章于 2023-03-25 00:10:31 发布