线性表的合并
#include<iostream.h>
#include<stdlib.h>
#include <malloc.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int
typedef struct
{
ElemType *elem;
int length;
int listsize;
}List;
void mergeList(List La,List Lb,List &Lc)
{
//InitList(Lc);
ElemType *pa,*pb,*pc,*pa_last,*pb_last;
pa=La.elem;pb=Lb.elem;
Lc.length=La.length+Lb.length;
pc=Lc.elem=(ElemType*)malloc(Lc.length*sizeof(ElemType));
if(!Lc.elem) exit(0);
pa_last=La.elem+La.length-1;
pb_last=Lb.elem+Lb.length-1;
while(pa<=pa_last&&pb<=pb_last)
{
if(*pa<=*pb)
*pc++=*pa++;
else
*pc++=*pb++;
while(pa<=pa_last)
{
*pc++=*pa++;
}
while(pb<=pb_last)
{
*pc++=*pb++;
}
}
}
void main()
{
List La,Lb,Lc;
int num;
cout<<"请输入第一组元素的个数:";
cin>>num;
La.length=num;
cout<<"请输入第一组数据:";
int *p=new int[num];
for(int i=1;i<=num;i++)
{
cin>>p[i];
cout<<" ";
}
La.elem=p;
cout<<"请输入第二组元素的个数:";
cin>>num;
Lb.length=num;
cout<<"请输入第二组数据:";
int *m=new int [num];
for(i=1;i<=num;i++)
{
cin>>m[i];
cout<<" ";
}
Lb.elem=m;
mergeList(La,Lb,Lc);
for(i=1;i<=Lc.length;i++)
{
cout<<*(Lc.elem+i-1)<<" "<<endl;
}
}
为什么这个程序输出的结果没有将两个线性表按非递减的顺序合并输出呢?
[解决办法]
while(pa<=pa_last&&pb<=pb_last)
{
if(*pa<=*pb)
*pc++=*pa++;
else
*pc++=*pb++;
} while(pa<=pa_last)
{
*pc++=*pa++;
}
while(pb<=pb_last)
{
*pc++=*pb++;
}
[解决办法]
这样试试看
void mergeList(List La,List Lb,List &Lc)
{
//InitList(Lc);
ElemType *pa,*pb,*pc,*pa_last,*pb_last;
pa=La.elem;pb=Lb.elem;
Lc.length=La.length+Lb.length;
pc=Lc.elem=(ElemType*)malloc(Lc.length*sizeof(ElemType));
if(!Lc.elem) exit(0);
pa_last=La.elem+La.length-1;
pb_last=Lb.elem+Lb.length-1;
while(pa<=pa_last&&pb<=pb_last)
{
if(*pa<=*pb)
*pc++=*pa++;
else
*pc++=*pb++;
}
while(pa<=pa_last)
{
*pc++=*pa++;
}
while(pb<=pb_last)
{
*pc++=*pb++;
}
}