将两个顺序存储的有序表合并成一个有序表的代码如下:
#include
#include
#include
#define MaxSize 50
typedef struct
{
int data[MaxSize];
int length;
}SqList;
void ListInsert(SqList *L,int i,int e)
{
int j;
if(i<1||i>L->length+1)
exit(-1);
if(L->length>=MaxSize)
exit(-1);
for(j=L->length;j>=i;j--)
L->data[j]=L->data[j-1];
L->data[i-1]=e;
L->length++;
}
void DispList(SqList *L)
{
int i;
for(i=0;i
printf("%d ",L->data[i]);
printf("\n");
}
void Exchange(SqList *A,SqList *B,SqList *C)
{
int i=0,j=0,k=0;
while(i
{
if(A->data[i]
C->data[k++]=A->data[i++];
else if(A->data[i]>B->data[j])
C->data[k++]=B->data[j++];
}
while(i
C->data[k++]=A->data[i++];
while(j
C->data[k++]=B->data[j++];
C->length=k;
}
void main()
{
SqList *A,*B,*C;
A=(SqList*)malloc(sizeof(SqList));
A->length=0;
B=(SqList*)malloc(sizeof(SqList));
B->length=0;
C=(SqList*)malloc(sizeof(SqList));
C->length=0;
ListInsert(A,1,1);
ListInsert(A,2,3);
ListInsert(A,3,5);
ListInsert(A,4,7);
ListInsert(A,5,9);
ListInsert(B,1,2);
ListInsert(B,2,4);
ListInsert(B,3,6);
ListInsert(B,4,8);
ListInsert(B,5,10);
ListInsert(B,6,12);
Exchange(A,B,C);
printf("顺序表A:");
DispList(A);
printf("顺序表B:");
DispList(B);
printf("顺序表C:");
DispList(C);
}
扩展资料:
第二种解法的核心代码
bool Merge(SeqList A, SeqList B, SeqList &C)
{//C为合并后的顺序表
if (A.length + B.length > C.MaxSize) return false;//超出最大存储空间
int i = 0, j = 0, k = 0;
while( i < A.length && j < B.length)
{
if (A.data[i] <= B.data[j])
C.data[k++] = A.data[i++];
else
C.data[k++] = B.data[j++];
}
while (i < A.length) C.data[k++] = A.data[i++];
while (j < B.length) C.data[k++] = B.data[j++];
C.length = k;
return true;
}
楼主你好
具体代码如下:
#include
#include
#define MAX 40
typedef struct
{
int data[MAX];
int length;
}LinkList;
void Initial_List(LinkList * &l,int n)//初始化顺序表
{
int i=0;
l=(LinkList *)malloc(sizeof(LinkList));
l->length = 0;
for(;i
l->length = n;
}
void Link(LinkList *l1,LinkList *l2,LinkList * &l3)//连接顺序表
{
int i,j;
l3=(LinkList *)malloc(sizeof(LinkList));
l3->length = l1->length + l2->length;
for(i=0;i
{
if(i
{
l3->data[i] = l1->data[i];
}
else
{
l3->data[i] = l2->data[i%(l1->length)];
}
}
for(i=0;i
{
for(j=i+1;j
{
if(l3->data[i]>l3->data[j])
{
int temp=l3->data[i];
l3->data[i]=l3->data[j];
l3->data[j]=temp;
}
}
}
}
void Disp_List(LinkList *l)
{
int i=0;
printf("output:\n");
for(;i
printf("%d ",l->data[i]);
printf("\n");
}
int main()
{
LinkList *l1,*l2,*l3;
int n;
printf("请输入第一个序列的元素个数:\n");
scanf("%d",&n);
printf("请输入第一个序列的所有元素:\n");
Initial_List(l1,n);
printf("请输入第二个序列的元素个数:\n");
scanf("%d",&n);
printf("请输入第二个序列的所有元素:\n");
Initial_List(l2,n);
Link(l1,l2,l3);
Disp_List(l3);
return 0;
}
希望能帮助你哈