写一个算法合并两个已排序的线性表。(用两种方法:数组表示的线性表(顺序表)和指针表示的线性表(链表))
要求:1、定义线性表节点的结构,并定义节点的型和位置的型。
2、定义线性表的基本操作
3、在1,2的基础上,完成本题。
4、在main函数中进行测试:先构建两个有序的线性表,然后合并这两个线性表。
#include <stdio.h>
#define maxlength 100
typedef int elementtype;
typedef int position;
struct LIST
{
elementtype element[maxlength];
int last;
};
void Insert(elementtype x,position p,LIST &L)
{
position q;
if(L.last>=maxlength)
printf("此表已满!\n");
else if(p>=maxlength||p<1)
printf("插入位置错误!\n");
else
{
for(q=L.last;q>=p;q--)
L.element[q+1]=L.element[q];
L.element[p]=x;
L.last=L.last+1;
}
return;
}
position Locate(elementtype x,LIST &L)
{
position p;
for(p=1;p<=L.last;p++)
if(L.element[p]==x)
return p;
return L.last+1;
}
elementtype Retrieve(position p,LIST &L)
{
if(p<=L.last)
return L.element[p];
else
printf("该位置不存在!\n");
return 0;
}
void Delete(elementtype x,position p,LIST &L)
{
position q;
if(p>L.last||p<1)
printf("该位置不存在!\n");
else
{
for(q=p;q<L.last;q++)
L.element[q]=L.element[q+1];
L.last=L.last-1;
}
return;
}
void print(LIST &L)
{
position p;
for(p=1;p<=L.last;p++)
printf("%d ",L.element[p]);
printf("\n");
return;
}
void merge(LIST &L1,LIST &L2,LIST &L3)
{
position p1=1,p2=1,p3=1;
while(p1<=L1.last&&p2<=L2.last)
{
if(L1.element[p1]<L2.element[p2])
{
Insert(L1.element[p1],p3,L3);
++p3;
++p1;
}
if(L1.element[p1]>=L2.element[p2])
{
Insert(L2.element[p2],p3,L3);
++p3;
++p2;
}
}
for(;p1<=L1.last;p1++)
Insert(L1.element[p1],p3,L3);
for(;p2<=L2.last;p2++)
Insert(L2.element[p2],p3,L3);
return;
}
int main()
{
LIST L1,L2,L3;
L1.last=0;
L2.last=0;
L3.last=0;
Insert(1, 1, L1);
Insert(3, 2, L1);
Insert(5, 3, L1);
Insert(7, 4, L1);
Insert(2, 1, L2);
Insert(4, 2, L2);
Insert(6, 3, L2);
Insert(8, 4, L2);
merge(L1,L2,L3);
print(L3);
return 0;
}