实现两个顺序表的合并(顺序表已递增)

实现两个顺序表的合并(顺序表已递增)

在学校自己做的实验报告,仅供参考,可能有误。
现在忘了··等考研复习时补充吧

 //(1)建立结构体
typedef struct {
	int* elem;
	int length;
	int listsize;
}sqlist;
//(2)初始化化线性表
void Initlist(sqlist& L) {
	L.elem = (int*)malloc(LIST_INIT_SIZE * sizeof(int));
	L.length = 0;
	L.listsize = LIST_INIT_SIZE;
}
//(3)创建线性表
void Creatlist(sqlist& q) {
	int a=0, i = 0;
	while (1) {
		cin >> a;
		if (a == -100)break;
		q.elem[i++] = a;
		q.length++;
	}
}
//(4)合并线性表
//设la,lb为两个有序递增线性表
void Mergelist(sqlist la, sqlist lb, sqlist &lc) {
	int* pa, * pb, * pc,*pa_last,*pb_last;
	pa = la.elem;
	pb = lb.elem;
	lc.listsize = lc.length = la.length + lb.length;
	pc = lc.elem = (int*)malloc(lc.listsize * sizeof(int));
	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++;
}

//(5)输出合并后的线性表
void Printlist(sqlist q) {
	int i = 0;
	
	for (; i < q.length; i++) {
		cout << q.elem[i];
	}

}
//(6)在main函数中声明结构体变量,调用所需函数
int main() {
	sqlist la, lb, lc;
	Initlist(la);
	Initlist(lb);
	Initlist(lc);
	Creatlist(la);
	Creatlist(lb);
	Mergelist(la, lb, lc);
	Printlist(lc);
	free(la.elem);
	free(lb.elem);
	
	return 0;
}

from nuister kjr

你可能感兴趣的:(数据结构)