实验要求:
已知两个非递减有序的线性表La和Lb,将La和Lb合并成一个线性表Lc,Lc也非递减有序。
分析:
这个题目不难,思路就是建立两个有序线性表,然后初始化另一个表Lc,用两个指针指向La,Lb的表头,开始比较,然后赋值给Lc,代码如下:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<time.h> //Random function needed
#define LIST_INIT_SIZE 10 //The length of La,Lb
typedef struct{
int *elem;
int length;
int listsize;
}SqList; //Define a struct named SqList;
SqList La,Lb,Lc; //Global variable
void Initlist(SqList &L);
void MergeList(SqList La,SqList Lb,SqList Lc);
void main()
{
srand(time(NULL)); //Initialize the elements of the list at random
printf("La:");
Initlist(La);
printf("Lb:");
Initlist(Lb);
printf("/nAfter merge/n/nLc:");
MergeList(La,Lb,Lc);
}
void Initlist(SqList &L) //Initialize the list and sort the list
{
L.elem =(int*)malloc(LIST_INIT_SIZE*sizeof(int));
int *p=&(L.elem[0]);
L.length=0,L.listsize =0;
for (int i=0;i<10;++i) //Initialize
{
*p=rand()%10;
L.length++;
L.listsize++;
p++;
}
int temp=0;
for (int i=0;i<L.length ;++i) //Bubble sort
for (int j=i;j<L.length ;++j)
if (L.elem [i]>L.elem [j])
temp=L.elem [i],L.elem [i]=L.elem [j],L.elem [j]=temp;
for (int i=0;i<L.length ;++i) //Output
printf("%d",L.elem [i]);
printf("/n");
}
void MergeList(SqList La,SqList Lb,SqList Lc) //Merge the lists
{
Lc.length =La.length +Lb.length ;
Lc.listsize=La.listsize+Lb.listsize;
Lc.elem =(int *)malloc(Lc.listsize *sizeof(int)); //Dynamic assign a new space
int *pa=&(La.elem[0]);
int *pb=&(Lb.elem[0]);
int *pc=&(Lc.elem[0]);
while (pa<=&(La.elem[La.length -1])&&pb<=&(Lb.elem[Lb.length -1])) //Merge
{
if (*pa<=*pb){
*pc++=*pa++;
}
else{
*pc++=*pb++;
}
}
while (pa<=&(La.elem[La.length -1])){ //Copy the last few elements to Lc
*pc++=*pa++;
}
while (pb<=&(Lb.elem[Lb.length -1])){ //Copy the last few elements to Lc
*pc++=*pb++;
}
pc=Lc.elem ;
while(pc<=&(Lc.elem[Lc.length -1])) //Output
{
printf("%d",*pc++);
}
printf("/n/n");
}