给定两个已排序的表L1和L2 只使用基本的表操作编写计算L1∪L2的过程 并集

数据结构与算法分析——c语言描述 练习3.5 答案

#include"list.h"
#include<stdio.h>

List Union(List l1, List l2) {
	List u = CreatList();
	Position p1 = First(l1);
	Position p2 = First(l2);
	Position resultPos = u;
	while (p1&&p2) {
		if (Retrieve(p1) > Retrieve(p2)) {
			Insert(Retrieve(p2), resultPos);
			p2 = Advance(p2);
			resultPos = Advance(resultPos);
		}
		else if (Retrieve(p1) < Retrieve(p2)) {
			Insert(Retrieve(p1), resultPos);
			p1 = Advance(p1);
			resultPos = Advance(resultPos);
		}
		else {
			Insert(Retrieve(p1), resultPos);
			p1 = Advance(p1);
			p2 = Advance(p2);
			resultPos = Advance(resultPos);
		}
	}
	while (p1 != NULL) {
		Insert(Retrieve(p1), resultPos);
		p1 = Advance(p1);
		resultPos = Advance(resultPos);
	}
	while (p2 != NULL) {
		Insert(Retrieve(p2), resultPos);
		p2 = Advance(p2);
		resultPos = Advance(resultPos);
	}
	return u;
}

void printAll(List l) {
	Position p = Advance(l);
	while (p) {
		printf("%d ", Retrieve(p));
		p = Advance(p);
	}
}

int main() {
	List l, p;
	l = CreatList();
	p = CreatList();
	for (int i = 39; i >= 0; i-=2)
		Insert(i, l);
	for (int i = 20; i >= 0; i -= 2)
		Insert(i, p);
	printAll(Union(l, p));
}



你可能感兴趣的:(给定两个已排序的表L1和L2 只使用基本的表操作编写计算L1∪L2的过程 并集)