#define _CRT_SECURE_NO_WARNINGS//顺序表
#include <stdio.h>
#include <malloc.h>
//全局定义特殊变量
#define MAX 50
#define ok 1
#define OVERFLOW 0
//转定义区域
typedef int ElemType;
typedef int status;
typedef struct//定义一个初始化的顺序表
{
ElemType* elem;//基地址
int length;
}Sqlist;
status initlist(Sqlist &L)
{
L.elem = new ElemType[MAX];
if (!L.elem)
{
return OVERFLOW;
}
L.length = 0;
return ok;
}
status insertlist(Sqlist& L, int i,ElemType e)
{
int j;
if (i<1 || i>L.length + 1)
{
return 0;
}
if (L.length == MAX)
{
return 0;
}
for (j = L.length - 1; j >= i - 1; j--)
{
L.elem[j + 1] = L.elem[j];
}
L.elem[i - 1]=e;
++L.length;
return ok;
}
status MergeList_sq(Sqlist& L1, Sqlist& L2, Sqlist& L3)
{
ElemType* p1, * p2, * p3, * p1_last, * p2_last;
L3.length = L1.length + L2.length;
L3.elem = new ElemType[L3.length];
p1 = L1.elem; p2 = L2.elem; p3 = L3.elem;
p1_last = &L1.elem[L1.length];
p2_last = &L2.elem[L2.length];
while (p1 != p1_last && p2 != p2_last)
{
if (*p1 <= *p2)
{
*p3++ = *p1++;
}
else
{
*p3++ = *p2++;
}
}
while (p1 != p1_last)
{
*p3++ = *p1++;
}
while (p2 != p2_last)
{
*p3++ = *p2++;
}
return ok;
}
void Displist(Sqlist L)
{
int i=0;
while (i < L.length)
{
printf("%d ", L.elem[i]);
i++;
}
printf("\n");
}
int main()
{
int a, f , i;
ElemType e = 0;
Sqlist L1;//定义好顺序表
Sqlist L2;//定义好顺序表
Sqlist L3;//定义好顺序表
initlist(L1);
initlist(L2);
for (i = 1,f=1; i < 10; i += 2,f++)
{
insertlist(L1, f, i);
}
for (i = 2, f = 1; i < 10; i += 2, f++)
{
insertlist(L2, f, i);
}
MergeList_sq(L1, L2, L3);
printf("生成的串1:");
Displist(L1);
printf("生成的串2:");
Displist(L2);
printf("合并的串:");
Displist(L3);
return ok;
}
使用的编译器环境是vs2019,源文件后缀是.cpp